Follow links to add evaluation to evaluate
made it here ### gaussian_input_emin
made it here ### mc_harmonic
made it here ### mc_ising
made it here ### nwchem_input_emin
made it here ### plot_3d_sin
made it here ### plot_bar
made it here ### plot_contour
made it here ### plot_correlation
made it here ### plot_dual_axis
made it here ### plot_emoji
made it here ### plot_outside_legend
made it here ### plot_pointsize
made it here ### plot_sin
made it here ### plot_sin_polar
made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here ## Test Report ### Global Parameters * Engine = openai * T = 0.2
| Test | Run 0 | Run 1 | Run 2 | Run 3 | Run 4 |
|---|---|---|---|---|---|
| aa_polarity | Fail | Pass | Fail | Fail | Fail |
| adiabatic_expansion | Pass | Pass | Pass | Pass | Pass |
| alignment | Pass | Pass | Pass | Pass | Pass |
| angle | Pass | Pass | Pass | Pass | Pass |
| aromatic_aa | Pass | Pass | Pass | Pass | Pass |
| arrhenius | Pass | Pass | Pass | Pass | Fail |
| bimolecular | Pass | Pass | Pass | Pass | Pass |
| bb_rad | Pass | Pass | Pass | Pass | Pass |
| blast | Fail | Fail | Fail | Fail | Fail |
| bravais | Pass | Pass | Pass | Fail | Pass |
| canonicalize | Pass | Pass | Pass | Pass | Pass |
| carnot_efficiency | Pass | Pass | Pass | Pass | Pass |
| claussius | Pass | Pass | Pass | Pass | Pass |
| compare_electronegativity | Fail | Fail | Fail | Fail | Fail |
| condiff_1d | Pass | Pass | Pass | Pass | Pass |
| cubes | Pass | Pass | Pass | Pass | Pass |
| de_broglie | Pass | Pass | Pass | Pass | Pass |
| derivative1d-ch | Pass | Pass | Pass | Pass | Pass |
| derivative_2deg | Pass | Pass | Pass | Pass | Pass |
| descriptors | Pass | Pass | Pass | Fail | Pass |
| dipole | Pass | Pass | Pass | Pass | Pass |
| dou | Fail | Fail | Fail | Fail | Fail |
| eigen-ch | Pass | Pass | Pass | Pass | Pass |
| eigen | Pass | Pass | Pass | Pass | Pass |
| element_mass | Pass | Fail | Pass | Pass | Pass |
| element_name | Pass | Pass | Pass | Pass | Pass |
| energy_of_e | Pass | Pass | Pass | Pass | Pass |
| find_indices | Fail | Fail | Fail | Fail | Fail |
| force_constant | Fail | Fail | Fail | Fail | Fail |
| fourier_1d | Pass | Pass | Pass | Pass | Pass |
| freezing_depression | Pass | Pass | Pass | Pass | Pass |
| genpos | Fail | Fail | Fail | Fail | Fail |
| heating_water | Fail | Fail | Fail | Fail | Fail |
| hydrophobic_res | Pass | Fail | Fail | Fail | Fail |
| ideal_gas | Pass | Pass | Pass | Pass | Pass |
| integral | Fail | Fail | Fail | Fail | Fail |
| trap | Pass | Pass | Pass | Pass | Pass |
| invert_matrix | Pass | Pass | Pass | Pass | Pass |
| iupac2smiles | Fail | Fail | Fail | Fail | Fail |
| kld | Pass | Pass | Pass | Pass | Pass |
| langevin_dynamics | Fail | Fail | Fail | Fail | Fail |
| weighted-least-squares | Pass | Pass | Fail | Fail | Fail |
| lipinski_rule_of_five | Pass | Pass | Pass | Pass | Pass |
| mape | Fail | Fail | Fail | Fail | Fail |
| mapping_operator | Fail | Fail | Fail | Fail | Fail |
| matpow | Pass | Pass | Pass | Pass | Pass |
| matrix_factorial | Pass | Pass | Pass | Pass | Pass |
| max-boltz | Pass | Pass | Pass | Pass | Fail |
| michaelis | Pass | Pass | Pass | Pass | Pass |
| mol_charge | Fail | Fail | Fail | Pass | Fail |
| net_charge | Pass | Pass | Pass | Pass | Pass |
| solve_ode | Fail | Fail | Fail | Fail | Fail |
| ohe | Fail | Fail | Fail | Fail | Fail |
| osmotic_pressure | Pass | Pass | Pass | Pass | Pass |
| pair_wise | Fail | Fail | Fail | Fail | Fail |
| pi | Pass | Pass | Pass | Pass | Pass |
| pib_1d | Pass | Pass | Pass | Pass | Pass |
| pred_interval | Pass | Fail | Fail | Pass | Pass |
| pubchem | Fail | Fail | Fail | Fail | Fail |
| pyscf_energy | Fail | Fail | Fail | Fail | Fail |
| qed | Fail | Fail | Fail | Fail | Fail |
| quantile | Fail | Pass | Fail | Fail | Fail |
| random_walk | Fail | Fail | Pass | Fail | Pass |
| rank | Pass | Pass | Pass | Pass | Pass |
| remove-water | Pass | Pass | Pass | Fail | Pass |
| rms_velocity | Pass | Fail | Pass | Fail | Fail |
| rmse | Pass | Pass | Pass | Pass | Pass |
| rog | Pass | Pass | Pass | Pass | Pass |
| sasa | Fail | Fail | Pass | Pass | Fail |
| scaffold | Fail | Fail | Fail | Fail | Fail |
| seq-align | Fail | Fail | Fail | Fail | Pass |
| seq-trans | Pass | Pass | Pass | Pass | Fail |
| sequence | Pass | Fail | Pass | Pass | Pass |
| sle | Fail | Fail | Fail | Fail | Fail |
| spectral_r | Pass | Pass | Pass | Pass | Pass |
| find_peaks | Fail | Fail | Fail | Fail | Fail |
| speed_of_sound | Fail | Fail | Fail | Fail | Fail |
| substructure | Fail | Fail | Fail | Fail | Fail |
| tanimoto | Pass | Fail | Pass | Pass | Pass |
| unbdistance | Fail | Fail | Fail | Fail | Fail |
aa_polarity
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
[insert]
return countimport math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for i in sequence:
if i == 'R' or i == 'K' or i == 'D' or i == 'E' or i == 'Q' or i == 'N' or i == 'H' or i == 'S' or i == 'T' or i == 'Y' or i == 'C' or i == 'M' or i == 'W':
count += 1
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for i in sequence:
if i == 'S' or i == 'T' or i == 'N' or i == 'Q' or i == 'Y' or i == 'C' or i == 'M' or i == 'W':
count += 1
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for i in sequence:
if i == 'R' or i == 'K' or i == 'D' or i == 'E' or i == 'Q' or i == 'N' or i == 'H' or i == 'S' or i == 'T' or i == 'Y' or i == 'C' or i == 'M' or i == 'W':
count += 1
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for i in sequence:
if i == "R" or i == "K" or i == "D" or i == "E" or i == "Q" or i == "N" or i == "H" or i == "S" or i == "T" or i == "Y" or i == "C" or i == "W":
count += 1
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for i in sequence:
if i == 'S' or i == 'T' or i == 'N' or i == 'Q' or i == 'C' or i == 'M' or i == 'K' or i == 'R' or i == 'H' or i == 'D' or i == 'E' or i == 'Y' or i == 'W':
count += 1
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
adiabatic_expansion
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
[insert]
return T2
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1*(P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1*(P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1*(P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1*(P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1*(P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
alignment
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
[insert]
return trajimport mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj.superpose(traj, frame=frame_index)
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
Success
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj.superpose(traj, frame=frame_index)
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
Success
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj.superpose(traj, frame=frame_index)
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
Success
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj.superpose(traj, frame=frame_index)
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
Success
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj.superpose(traj, frame=frame_index)
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
Success
angle
import numpy as np
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
[insert]
return angleimport numpy as np
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
cosang = np.dot(v1,v2)
sinang = np.linalg.norm(np.cross(v1,v2))
angle = np.arctan2(sinang, cosang)
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
v1_u = v1 / np.linalg.norm(v1)
v2_u = v2 / np.linalg.norm(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
v1 = np.array(v1)
v2 = np.array(v2)
angle = np.arccos(np.dot(v1,v2)/(np.linalg.norm(v1)*np.linalg.norm(v2)))
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
v1 = np.array(v1)
v2 = np.array(v2)
v1 = v1/np.linalg.norm(v1)
v2 = v2/np.linalg.norm(v2)
angle = np.arccos(np.dot(v1,v2))
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
v1_u = v1 / np.linalg.norm(v1)
v2_u = v2 / np.linalg.norm(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
aromatic_aa
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
[insert]
return countimport math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
count = 0
for i in sequence:
if i == 'F' or i == 'Y' or i == 'W':
count += 1
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
aromatic_residues = ['F', 'W', 'Y']
count = 0
for i in sequence:
if i in aromatic_residues:
count += 1
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
aromatic_aa = ['F', 'Y', 'W']
count = 0
for aa in sequence:
if aa in aromatic_aa:
count += 1
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
count = 0
for aa in sequence:
if aa == 'F' or aa == 'Y' or aa == 'W':
count += 1
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
count = 0
for i in sequence:
if i == 'F' or i == 'Y' or i == 'W':
count += 1
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
arrhenius
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
[insert]
return k1import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = k2*math.exp((-Ea/8.314)*((1/T1)-(1/T2)))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = k2*math.exp((Ea/8.314)*((1/T2)-(1/T1)))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = k2*math.exp((-Ea/8.314)*(1/T1-1/T2))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = k2*math.exp((-Ea/8.314)*(1/T1-1/T2))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = k2*math.exp((Ea/8.314)*((1/T1)-(1/T2)))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
bimolecular
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
[insert]
return rateimport math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*A*B
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*A*B
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*A*B
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*A*B
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*A*B
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
bb_rad
import numpy as np
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
[insert]
return Bimport numpy as np
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
h = 6.62607004e-34
c = 299792458
k = 1.38064852e-23
B = 2*h*c**2/lam**5 * 1/(np.exp(h*c/(lam*k*T))-1)
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
c = 3e8
h = 6.626e-34
k = 1.38e-23
B = 2*h*c**2/lam**5*1/(np.exp(h*c/(lam*k*T))-1)
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
h = 6.62607004e-34 # Planck's constant in SI unit
c = 299792458 # speed of light in SI unit
k = 1.38064852e-23 # Boltzmann's constant in SI unit
B = 2*h*c**2/lam**5/(np.exp(h*c/(lam*k*T))-1)
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
h = 6.626e-34
c = 3e8
k = 1.38e-23
B = 2*h*c**2/lam**5 * 1/(np.exp(h*c/(lam*k*T))-1)
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
h = 6.626e-34
c = 3.0e+8
k = 1.38e-23
B = 2*h*c**2/lam**5/(np.exp(h*c/(lam*k*T))-1)
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
blast
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
[insert]
return e, idimport requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# Submit BLAST search
r = requests.post('https://blast.ncbi.nlm.nih.gov/Blast.cgi',
data={'QUERY': seq,
'DATABASE': 'nr',
'PROGRAM': 'blastp',
'CMD': 'Put'})
# Get result
r = requests.get(r.url)
soup = BeautifulSoup(r.text, 'html.parser')
# Parse MSA
msa = soup.find_all('pre')[0].text.split('\n')
msa = [i for i in msa if i != '']
msa = [i for i in msa if i[0] != '>']
msa = [i for i in msa if i[0] != ' ']
# Get e score and id
e = soup.find_all('pre')[1].text.split('\n')[1].split()[-1]
id = soup.find_all('pre')[1].text.split('\n')[1].split()[1]
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
list index out of range
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1. import packages
import requests
from bs4 import BeautifulSoup
import numpy as np
# 2. Submit BLAST search with sequences
url = 'https://blast.ncbi.nlm.nih.gov/Blast.cgi'
params = {'QUERY': seq, 'DATABASE': 'nr', 'PROGRAM': 'blastp', 'FILTER': 'L', 'EXPECT': '1e-3', 'CMD': 'Put'}
r = requests.get(url, params=params)
soup = BeautifulSoup(r.text, 'html.parser')
# 3. Get result
result = soup.find('pre')
# 4. Parse MSA
result = result.text.split('\n')
result = [i for i in result if i.startswith('>')]
result = [i.split(' ')[0] for i in result]
result = [i.replace('>', '') for i in result]
result = [i.split('|')[3] for i in result]
result = [i.split('.')[0] for i in result]
result = [i.split('_')[0] for i in result]
# 5. Return a tuple of e score, id of top match
e = float(soup.find('td', text='Expect').find_next_sibling('td').text)
id = result[0]
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
'NoneType' object has no attribute 'text'
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1.
import requests
from bs4 import BeautifulSoup
import numpy as np
# 2.
url = "https://blast.ncbi.nlm.nih.gov/Blast.cgi"
payload = {'QUERY': seq, 'PROGRAM': 'blastp', 'DATABASE': 'nr', 'CMD': 'Put'}
r = requests.post(url, data=payload)
# 3.
url = r.url
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
# 4.
msa = soup.find_all('pre')[1].text
msa = msa.split('\n')
msa = [i.split() for i in msa]
msa = np.array(msa)
msa = msa[msa[:,0] != 'Query=']
msa = msa[msa[:,0] != '>']
msa = msa[msa[:,0] != '']
msa = msa[msa[:,0] != 'Lambda']
msa = msa[msa[:,0] != 'Gapped']
msa = msa[msa[:,0] != 'Matrix:']
msa = msa[msa[:,0] != 'Gap']
msa = msa[msa[:,0] != 'Extension:']
msa = msa[msa[:,0] != 'Frame:']
msa = msa[msa[:,0] != 'Query']
msa = msa[msa[:,0] != 'Score']
msa = msa[msa[:,0] != 'E']
msa = msa[msa[:,0] != 'Identities']
msa = msa[msa[:,0] != 'Positives']
msa = msa[msa[:,0] != 'Strand']
msa = msa[msa[:,0] != 'Query:']
msa = msa[msa[:,0] != 'Sbjct:']
msa = msa[msa[:,0] != 'Length=']
msa = msa[msa[:,0] != 'Score =']
msa = msa[msa[:,0] != 'Expect =']
msa = msa[msa[:,0] != 'Identities =']
msa = msa[msa[:,0] != 'Positives =']
msa = msa[msa[:,0] != 'Strand =']
msa = msa[msa[:,0] != 'Frame =']
msa = msa[msa[:,0] != 'Query']
msa = msa[msa[:,0] != 'Sbjct']
msa = msa[msa[:,0] != 'Lambda']
msa = msa[msa[:,0] != 'Gapped']
msa = msa[msa[:,0] != 'Matrix:']
msa = msa[msa[:,0] != 'Gap']
msa = msa[msa[:,0] != 'Extension:']
msa = msa[msa[:,0] != 'Frame:']
msa = msa[msa[:,0] != 'Query']
msa = msa[msa[:,0] != 'Score']
msa = msa[msa[:,0] != 'E']
msa = msa[msa[:,0] != 'Identities']
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
list index out of range
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1. import packages
from Bio.Blast import NCBIWWW
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Alphabet import IUPAC
from Bio.Blast import NCBIXML
from Bio import AlignIO
import numpy as np
import pandas as pd
import requests
from bs4 import BeautifulSoup
# 2. Submit BLAST search with sequences
result_handle = NCBIWWW.qblast("blastn", "nt", seq)
# 3. Get result
blast_records = NCBIXML.parse(result_handle)
# 4. Parse MSA
E_VALUE_THRESH = 0.04
for blast_record in blast_records:
for alignment in blast_record.alignments:
for hsp in alignment.hsps:
if hsp.expect < E_VALUE_THRESH:
print('****Alignment****')
print('sequence:', alignment.title)
print('length:', alignment.length)
print('e value:', hsp.expect)
print(hsp.query[0:75] + '...')
print(hsp.match[0:75] + '...')
print(hsp.sbjct[0:75] + '...')
e = hsp.expect
id = alignment.title
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
Error message from NCBI: Message ID#24 Error: Failed to read the Blast query: Protein FASTA provided for nucleotide sequence
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1. import packages
import requests
from bs4 import BeautifulSoup
# 2. Submit BLAST search with sequences
url = 'https://blast.ncbi.nlm.nih.gov/Blast.cgi'
params = {'QUERY': seq,
'PROGRAM': 'blastp',
'DATABASE': 'swissprot',
'FILTER': 'L',
'EXPECT': '1e-3',
'HITLIST_SIZE': '1',
'ALIGNMENTS': '1',
'ALIGNMENT_VIEW': 'Pairwise',
'DESCRIPTIONS': '1',
'FORMAT_TYPE': 'HTML',
'NCBI_GI': 'on',
'CMD': 'Put'}
r = requests.get(url, params=params)
# 3. Get result
soup = BeautifulSoup(r.text, 'html.parser')
result = soup.find('pre')
result = result.text
# 4. Parse MSA
result = result.split('\n')
result = [i for i in result if i != '']
result = [i for i in result if i[0] != '>']
result = [i for i in result if i[0] != ' ']
result = [i for i in result if i[0] != 'L']
result = [i for i in result if i[0] != 'S']
result = [i for i in result if i[0] != 'Q']
result = [i for i in result if i[0] != 'T']
result = [i for i in result if i[0] != 'M']
result = [i for i in result if i[0] != 'I']
result = [i for i in result if i[0] != 'G']
result = [i for i in result if i[0] != 'A']
result = [i for i in result if i[0] != 'P']
result = [i for i in result if i[0] != 'V']
result = [i for i in result if i[0] != 'H']
result = [i for i in result if i[0] != 'F']
result = [i for i in result if i[0] != 'Y']
result = [i for i in result if i[0] != 'W']
result = [i for i in result if i[0] != 'K']
result = [i for i in result if i[0] != 'R']
result = [i for i in result if i[0] != 'D']
result = [i for i in result if i[0] != 'E']
result = [i for i in result if i[0] != 'N']
result = [i for i in result if i[0] != 'C']
# 5. Return a tuple of e score, id of top match
e = result[0].split(' ')[-1]
id = result[1].split(' ')[-1]
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
'NoneType' object has no attribute 'text'
bravais
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
[insert]
return nameimport math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
name = None
if group_number in range(1, 3):
name = "triclinic"
elif group_number in range(3, 16):
name = "monoclinic"
elif group_number in range(16, 75):
name = "orthorhombic"
elif group_number in range(75, 143):
name = "tetragonal"
elif group_number in range(143, 168):
name = "trigonal"
elif group_number in range(168, 195):
name = "hexagonal"
elif group_number in range(195, 231):
name = "cubic"
else:
sys.exit("Invalid space group number")
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
Success
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
if group_number < 1 or group_number > 230:
sys.exit("Invalid space group number")
name = ""
if group_number <= 2:
name = "triclinic"
elif group_number <= 15:
name = "monoclinic"
elif group_number <= 74:
name = "orthorhombic"
elif group_number <= 142:
name = "tetragonal"
elif group_number <= 167:
name = "trigonal"
elif group_number <= 194:
name = "hexagonal"
elif group_number <= 230:
name = "cubic"
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
Success
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
name = None
if group_number >= 1 and group_number <= 2:
name = 'triclinic'
elif group_number >= 3 and group_number <= 15:
name = 'monoclinic'
elif group_number >= 16 and group_number <= 74:
name = 'orthorhombic'
elif group_number >= 75 and group_number <= 142:
name = 'tetragonal'
elif group_number >= 143 and group_number <= 167:
name = 'trigonal'
elif group_number >= 168 and group_number <= 194:
name = 'hexagonal'
elif group_number >= 195 and group_number <= 230:
name = 'cubic'
else:
sys.exit('Space group number out of range')
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
Success
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
name = ""
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
Success
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
if group_number < 1 or group_number > 230:
raise ValueError("Invalid space group number")
name = ""
if group_number <= 2:
name = "triclinic"
elif group_number <= 15:
name = "monoclinic"
elif group_number <= 74:
name = "orthorhombic"
elif group_number <= 142:
name = "tetragonal"
elif group_number <= 167:
name = "trigonal"
elif group_number <= 194:
name = "hexagonal"
elif group_number <= 230:
name = "cubic"
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
Success
canonicalize
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
[insert]
return canon_listimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canon_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canon_list.append(Chem.MolToSmiles(mol))
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canon_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canon_list.append(Chem.MolToSmiles(mol, isomericSmiles=True))
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canon_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canon_list.append(Chem.MolToSmiles(mol))
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canon_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canon_list.append(Chem.MolToSmiles(mol))
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canon_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canon_list.append(Chem.MolToSmiles(mol, isomericSmiles=True))
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
carnot_efficiency
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
[insert]
return eps
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = 1 - (T_cold/T_hot)
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = 1 - T_cold/T_hot
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = 1 - (T_cold/T_hot)
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = 1 - (T_cold/T_hot)
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = 1 - (T_cold / T_hot)
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
claussius
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
[insert]
return P2
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = P1*math.exp((HVap/8.314)*((1/T1)-(1/T2)))
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = P1*math.exp((HVap/8.314)*(1/T1 - 1/T2))
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = P1*math.exp((HVap/8.314)*((1/T1)-(1/T2)))
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = P1*math.exp((HVap/8.314)*(1/T1 - 1/T2))
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = P1 * math.exp((HVap/8.314) * ((1/T1) - (1/T2)))
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
compare_electronegativity
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
[insert]
return resultimport math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
result = mendeleev.element(element1).electronegativity > mendeleev.element(element2).electronegativity
return result
result = True if compare_electronegativity("O","C") else FalseOutput:
'>' not supported between instances of 'method' and 'method'
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
result = False
if mendeleev.element(element1).pauling > mendeleev.element(element2).pauling:
result = True
return result
result = True if compare_electronegativity("O","C") else FalseOutput:
'Element' object has no attribute 'pauling'
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
result = mendeleev.element(element1).electronegativity > mendeleev.element(element2).electronegativity
return result
result = True if compare_electronegativity("O","C") else FalseOutput:
'>' not supported between instances of 'method' and 'method'
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
result = mendeleev.element(element1).electronegativity > mendeleev.element(element2).electronegativity
return result
result = True if compare_electronegativity("O","C") else FalseOutput:
'>' not supported between instances of 'method' and 'method'
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
result = False
if mendeleev.element(element1).electronegativity > mendeleev.element(element2).electronegativity:
result = True
return result
result = True if compare_electronegativity("O","C") else FalseOutput:
'>' not supported between instances of 'method' and 'method'
condiff_1d
import numpy as np
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
[insert]
return diffimport numpy as np
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.zeros(len(x)-1)
for i in range(len(x)-1):
diff[i] = x[i+1] - x[i]
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.zeros(len(x)-1)
for i in range(len(x)-1):
diff[i] = x[i+1] - x[i]
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.zeros(len(x)-1)
for i in range(len(x)-1):
diff[i] = x[i+1] - x[i]
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.zeros(len(x)-1)
for i in range(len(x)-1):
diff[i] = x[i+1] - x[i]
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.zeros(len(x)-1)
for i in range(len(x)-1):
diff[i] = x[i+1] - x[i]
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
cubes
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
[insert]
return simport math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = 0
for i in range(1, n+1):
s += i**3
return s
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = 0
for i in range(1, n+1):
s += i**3
return s
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = 0
for i in range(1, n+1):
s += i**3
return s
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = 0
for i in range(1, n+1):
s += i**3
return s
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = 0
for i in range(1,n+1):
s += i**3
return s
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
de_broglie
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
[insert]
return limport math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
h = 6.626e-34
l = h/(m*v)
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
h = 6.62607004e-34
l = h/(m*v)
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
l = h/(m*v)
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
h = 6.62607004e-34
l = h/(m*v)
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
h = 6.62606957e-34
l = h/(m*v)
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
derivative1d-ch
import numpy as np
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
[insert]
return dimport numpy as np
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
d = 2*a*x + b
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
d = 2*a*x + b
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
d = 2*a*x + b
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
d = 2*a*x + b
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
d = 2*a*x + b
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
derivative_2deg
import numpy as np
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
[insert]
return derivimport numpy as np
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = 2*a*x + b
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = 2*a*x + b
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = 2*a*x + b
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = 2*a*x + b
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = 2*a*x + b
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
descriptors
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
[insert]
return descriptorsimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
descriptors.append([
Descriptors.MolWt(mol),
Descriptors.ExactMolWt(mol),
Descriptors.NumValenceElectrons(mol),
Descriptors.NumRadicalElectrons(mol),
Descriptors.NumHDonors(mol),
Descriptors.NumHAcceptors(mol),
Descriptors.TPSA(mol),
Descriptors.LabuteASA(mol)
])
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
descriptors.append([
Descriptors.MolWt(mol),
Descriptors.MolLogP(mol),
Descriptors.NumHDonors(mol),
Descriptors.NumHAcceptors(mol),
Descriptors.NumRotatableBonds(mol),
Descriptors.NumValenceElectrons(mol),
Descriptors.TPSA(mol),
Descriptors.NumAromaticRings(mol)
])
descriptors = np.array(descriptors)
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
descriptors.append([Descriptors.MolWt(mol),
Descriptors.NumValenceElectrons(mol),
Descriptors.NumRadicalElectrons(mol),
Descriptors.NumHDonors(mol),
Descriptors.NumHAcceptors(mol),
Descriptors.TPSA(mol),
Descriptors.LabuteASA(mol),
Descriptors.ExactMolWt(mol)])
descriptors = np.array(descriptors)
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
descriptors.append(np.array(list(MoleculeDescriptors.MolecularDescriptorCalculator([x[0] for x in Descriptors._descList]).CalcDescriptors(mol))))
descriptors = np.array(descriptors)
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
descriptors.append([
Descriptors.MolLogP(mol),
Descriptors.MolWt(mol),
Descriptors.NumHDonors(mol),
Descriptors.NumHAcceptors(mol),
Descriptors.TPSA(mol),
Descriptors.NumRotatableBonds(mol),
Descriptors.NumValenceElectrons(mol),
Descriptors.RingCount(mol)
])
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
dipole
import numpy as np
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
[insert]
return dipole_momentimport numpy as np
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole_moment = np.sum(coordinates*charges[:,np.newaxis], axis=0)
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
Success
import numpy as np
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole_moment = np.zeros(3)
for i in range(len(coordinates)):
dipole_moment += charges[i] * coordinates[i]
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
Success
import numpy as np
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole_moment = np.sum(coordinates*charges[:,np.newaxis], axis=0)
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
Success
import numpy as np
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole_moment = np.zeros(3)
for i in range(len(charges)):
dipole_moment += charges[i]*coordinates[i]
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
Success
import numpy as np
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole_moment = np.dot(coordinates.T, charges)
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
Success
dou
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
[insert]
return dimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return 0
else:
return rdMolDescriptors.CalcNumRotatableBonds(mol)
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return None
else:
return Descriptors.NumRadicalElectrons(mol)
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return None
d = Descriptors.NumRotatableBonds(mol)
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
d = Descriptors.NumRotatableBonds(mol)
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
m = Chem.MolFromSmiles(smiles)
d = Descriptors.NumRotatableBonds(m)
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
Success
eigen-ch
import numpy as np
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w,v=np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
eigen
import numpy as np
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
[insert]
return w,vimport numpy as np
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
element_mass
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
[insert]
return massimport math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.element(element_symbol).mass
if mass == None:
print("Element symbol not found")
sys.exit()
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
Success
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.element(element_symbol).mass
if mass == None:
print "Error: element symbol not found"
sys.exit(1)
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
Missing parentheses in call to 'print'. Did you mean print("Error: element symbol not found")? (<string>, line 12)
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.element(element_symbol).mass
if mass == None:
print("Error: element symbol not found")
sys.exit()
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
Success
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.element(element_symbol).mass
if mass == None:
print("Error: Element symbol not found")
sys.exit()
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
Success
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.element(element_symbol).mass
if mass is None:
sys.exit("Error: element mass not found")
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
Success
element_name
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
[insert]
return simport math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.element(element_number).symbol
return s
result = True if symbol(26).lower()=="fe" else FalseOutput:
Success
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.element(element_number).symbol
return s
result = True if symbol(26).lower()=="fe" else FalseOutput:
Success
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.element(element_number).symbol
return s
result = True if symbol(26).lower()=="fe" else FalseOutput:
Success
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.element(element_number).symbol
return s
result = True if symbol(26).lower()=="fe" else FalseOutput:
Success
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.element(element_number).symbol
return s
result = True if symbol(26).lower()=="fe" else FalseOutput:
Success
energy_of_e
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
[insert]
return energyimport math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = -13.6*(1/n**2)
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = -13.6 * (1 / (n ** 2))
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = -13.6*(1/n**2)
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = -13.6 * (1/n**2)
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = -13.6*(1/n**2)
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
find_indices
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
[insert]
return idximport mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
traj = md.load(pdb_file)
idx = np.where(traj.topology.select('name CA'))[0][:2]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
traj = md.load(pdb_file)
idx = np.where(traj.top.select("name CA"))[0][:2]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
traj = md.load(pdb_file)
topology = traj.topology
idx = topology.select('name CA')
idx = idx[0:2]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
traj = md.load(pdb_file)
idx = np.where(traj.topology.select('name CA'))[0][:2]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
traj = md.load(pdb_file)
idx = np.where(traj.topology.select('name CA'))[0][:2]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Constant' object has no attribute 'kind'
force_constant
import numpy as np
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
[insert]
return kimport numpy as np
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = (1.0/wave_len)*(1.0/wave_len)*(1.0/2.0)*(m1*m2)/(m1+m2)
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = (1.98644568e-23*(wave_len*1e2)**2)/((m1*m2)/(m1+m2))
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = (1.0/wave_len)*(1.0/wave_len)*(1.0/2.0)*(m1*m2)/(m1+m2)
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = (1.98644568e-23*(1e2)**2)/(wave_len*(m1*m2)/(m1+m2))
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = (1.0/2.0)*(1.0/m1+1.0/m2)*(1.0/wave_len)*(1.0/2.194746313705e5)
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
Success
fourier_1d
import numpy as np
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
[insert]
return wimport numpy as np
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
w = np.fft.fft(x)
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
Success
import numpy as np
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
w = np.fft.fft(x)
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
Success
import numpy as np
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
w = np.fft.fft(x)
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
Success
import numpy as np
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
N = len(x)
w = np.zeros(N, dtype=complex)
for k in range(N):
for n in range(N):
w[k] += x[n] * np.exp(-2j * np.pi * k * n / N)
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
Success
import numpy as np
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
w = np.fft.fft(x)
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
Success
freezing_depression
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
[insert]
return deltaTimport math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
deltaT = Kf*m
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
Success
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
deltaT = Kf*m
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
Success
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
deltaT = Kf*m
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
Success
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
deltaT = Kf*m
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
Success
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
deltaT = Kf*m
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
Success
genpos
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
[insert]
return generatorsimport requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = "http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-matrix_generators?gnum="+str(gnum)
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
table = soup.find_all('table')[0]
generators = []
for row in table.find_all('tr'):
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
generators.append([float(ele) for ele in cols])
generators = np.array(generators)
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
list index out of range
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = 'http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-matgen'
params = {'gnum':gnum}
r = requests.get(url, params=params)
soup = BeautifulSoup(r.text, 'html.parser')
table = soup.find_all('table')[1]
rows = table.find_all('tr')
generators = []
for row in rows:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
generators.append([float(ele) for ele in cols])
generators = np.array(generators)
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
list index out of range
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = 'http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-gen-matrices?gnum=' + str(gnum)
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
table = soup.find_all('table')[0]
generators = []
for row in table.find_all('tr'):
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
generators.append(cols)
generators = np.array(generators)
generators = generators[:,1:4]
generators = generators.astype(float)
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
list index out of range
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = 'http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-matrix_gen?gnum=' + str(gnum)
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
table = soup.find_all('table')[1]
generators = []
for row in table.find_all('tr')[1:]:
cols = row.find_all('td')
generators.append(np.array([[float(cols[1].text), float(cols[2].text), float(cols[3].text)],
[float(cols[4].text), float(cols[5].text), float(cols[6].text)],
[float(cols[7].text), float(cols[8].text), float(cols[9].text)]]))
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
list index out of range
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = 'http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-matgen?gnum=' + str(gnum)
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
table = soup.find_all('table')[1]
generators = []
for row in table.find_all('tr')[1:]:
cols = row.find_all('td')
generators.append(np.array([float(cols[1].text), float(cols[2].text), float(cols[3].text)]))
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
list index out of range
heating_water
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
[insert]
return q
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = n * (4.184 * (T2 - T1))
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = n * (T2 - T1) * 4.184
print(q)
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = n*4.184*(T2-T1)
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = n*(T2-T1)*4.184
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = n * (T2 - T1) * 4.184
print("The energy required to heat", n, "moles of water from", T1, "to", T2, "is", q, "kcal.")
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
hydrophobic_res
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
[insert]
return residsimport mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
t = md.load(pdb_filename)
resids = []
for i, res in enumerate(t.topology.residues):
if res.is_water:
continue
if res.name in ['ALA', 'ILE', 'LEU', 'VAL', 'PHE', 'TRP', 'TYR', 'MET']:
resids.append(i)
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
Success
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
traj = md.load(pdb_filename)
resids = []
for i in range(traj.n_residues):
if traj.topology.residue(i).is_hydrophobic:
resids.append(i)
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
'Residue' object has no attribute 'is_hydrophobic'
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
traj = md.load(pdb_filename)
resids = []
for i in range(traj.n_residues):
if traj.topology.residue(i).is_hydrophobic:
resids.append(i)
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
'Residue' object has no attribute 'is_hydrophobic'
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
traj = md.load(pdb_filename)
resids = []
for i in range(traj.n_residues):
if traj.topology.residue(i).is_hydrophobic:
resids.append(i)
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
'Residue' object has no attribute 'is_hydrophobic'
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
traj = md.load(pdb_filename)
resids = []
for i in range(traj.n_residues):
if traj.topology.residue(i).is_hydrophobic:
resids.append(i)
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
'Residue' object has no attribute 'is_hydrophobic'
ideal_gas
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
[insert]
return Pimport math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.0821 # atm L / mol K
P = (n*R*T)/V
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.0821 #atm*L/mol*K
P = (n*R*T)/V
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.0821 # atm*L/mol*K
P = (n*R*T)/V
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.08205746 # atm L / mol K
P = n * R * T / V
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.0821 #atm*L/mol*K
P = (n*R*T)/V
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
integral
import numpy as np
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
[insert]
return integralimport numpy as np
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
integral = a*(b**2)/2 + b*c + c*d + d**2/2
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
Success
import numpy as np
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
integral = a*(b**2)/2 + b*c + c*d + d**2/2
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
Success
import numpy as np
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
integral = (a/5)*d**5 + (b/4)*d**4 + (c/3)*d**3 + (d/2)*d**2 + d
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
Success
import numpy as np
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
integral = (a/4)*(b**4) + (b/3)*(b**3) + (c/2)*(b**2) + d*b
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
Success
import numpy as np
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
integral = (a/4)*(b**4) + (b/3)*(b**3) + (c/2)*(b**2) + d*b
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
Success
trap
import numpy as np
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
[insert]
return integralimport numpy as np
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
h = (b-a)/n
x = np.linspace(a, b, n+1)
integral = 0.5*h*(f(x[0]) + f(x[-1]))
for i in range(1, n):
integral += h*f(x[i])
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
import numpy as np
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
h = (b-a)/n
integral = 0.5*(f(a) + f(b))
for i in range(1,n):
integral += f(a + i*h)
integral *= h
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
import numpy as np
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
h = (b-a)/n
x = np.linspace(a, b, n+1)
integral = 0.5*h*(f(x[0]) + f(x[-1]))
for i in range(1, n):
integral += h*f(x[i])
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
import numpy as np
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
h = (b-a)/n
integral = 0.5*f(a) + 0.5*f(b)
for i in range(1, n):
integral += f(a+i*h)
integral *= h
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
import numpy as np
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
h = (b - a)/n
integral = 0.5*f(a) + 0.5*f(b)
for i in range(1, n):
integral += f(a + i*h)
integral *= h
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
invert_matrix
import numpy as np
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
[insert]
return Ainvimport numpy as np
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
Ainv = np.linalg.inv(A)
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
import numpy as np
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
Ainv = np.linalg.inv(A)
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
import numpy as np
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
Ainv = np.linalg.inv(A)
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
import numpy as np
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
Ainv = np.linalg.inv(A)
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
import numpy as np
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
Ainv = np.linalg.inv(A)
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
iupac2smiles
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
[insert]
return SMILESimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(IUPAC)))
SMILES = Chem.MolToSmiles(mol)
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
Python argument types in
rdkit.Chem.rdmolfiles.MolToSmiles(NoneType)
did not match C++ signature:
MolToSmiles(RDKit::ROMol mol, bool isomericSmiles=True, bool kekuleSmiles=False, int rootedAtAtom=-1, bool canonical=True, bool allBondsExplicit=False, bool allHsExplicit=False, bool doRandom=False)
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolTo
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolTo
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(IUPAC)))
SMILES = Chem.MolToSmiles(mol)
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
Python argument types in
rdkit.Chem.rdmolfiles.MolToSmiles(NoneType)
did not match C++ signature:
MolToSmiles(RDKit::ROMol mol, bool isomericSmiles=True, bool kekuleSmiles=False, int rootedAtAtom=-1, bool canonical=True, bool allBondsExplicit=False, bool allHsExplicit=False, bool doRandom=False)
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(IUPAC)))
SMILES = Chem.MolToSmiles(mol)
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
Python argument types in
rdkit.Chem.rdmolfiles.MolToSmiles(NoneType)
did not match C++ signature:
MolToSmiles(RDKit::ROMol mol, bool isomericSmiles=True, bool kekuleSmiles=False, int rootedAtAtom=-1, bool canonical=True, bool allBondsExplicit=False, bool allHsExplicit=False, bool doRandom=False)
kld
import numpy as np
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
[insert]
return lossimport numpy as np
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = np.sum(np.where(true_data != 0, true_data * np.log(true_data / predicted_data), 0))
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
Success
import numpy as np
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = np.sum(np.where(true_data != 0, true_data * np.log(true_data / predicted_data), 0))
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
Success
import numpy as np
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = np.sum(np.where(true_data != 0, true_data * np.log(true_data / predicted_data), 0))
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
Success
import numpy as np
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = np.sum(true_data * np.log(true_data / predicted_data))
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
Success
import numpy as np
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = np.sum(np.where(true_data != 0, true_data * np.log(true_data / predicted_data), 0))
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
Success
langevin_dynamics
import numpy as np
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
[insert]
return x_traj, v_trajimport numpy as np
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(n_steps-1):
v_traj[i+1] = (v_traj[i] - F(x_traj[i])/m*dt - gamma/m*v_traj[i]*dt + np.sqrt(2*gamma*T/m)*np.random.normal()*np.sqrt(dt))
x_traj[i+1] = x_traj[i] + v_traj[i+1]*dt
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
Success
import numpy as np
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(n_steps-1):
x_traj[i+1] = x_traj[i] + dt*v_traj[i]
v_traj[i+1] = v_traj[i] + dt*(F(x_traj[i])/m - gamma*v_traj[i] + np.sqrt(2*gamma*T/m)*np.random.normal(0,1))
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
Success
import numpy as np
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(1,n_steps):
v_traj[i] = v_traj[i-1] - F(x_traj[i-1])*dt/m - gamma*v_traj[i-1]*dt + np.sqrt(2*gamma*T*dt)*np.random.normal()
x_traj[i] = x_traj[i-1] + v_traj[i]*dt
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
Success
import numpy as np
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(n_steps-1):
v_traj[i+1] = (v_traj[i] - dt*F(x_traj[i])/m - gamma*v_traj[i] + np.sqrt(2*gamma*T*dt)*np.random.normal())/(1+gamma*dt)
x_traj[i+1] = x_traj[i] + dt*v_traj[i+1]
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
Success
import numpy as np
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(n_steps-1):
v_traj[i+1] = (v_traj[i] - (F(x_traj[i])/m)*dt - gamma*v_traj[i]*dt + np.sqrt(2*gamma*T*dt)*np.random.normal())/(1+gamma*dt)
x_traj[i+1] = x_traj[i] + v_traj[i+1]*dt
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
Success
weighted-least-squares
import numpy as np
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
[insert]
return betaimport numpy as np
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
beta = np.linalg.inv(x.T.dot(np.diag(w)).dot(x)).dot(x.T).dot(np.diag(w)).dot(y)
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
Success
import numpy as np
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
beta = np.linalg.inv(x.T.dot(np.diag(w)).dot(x)).dot(x.T).dot(np.diag(w)).dot(y)
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
Success
import numpy as np
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
x = np.matrix(x)
y = np.matrix(y)
w = np.matrix(w)
beta = (x.T*w*x).I*x.T*w*y
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
shapes (3,100) and (1,100) not aligned: 100 (dim 1) != 1 (dim 0)
import numpy as np
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
x = np.matrix(x)
y = np.matrix(y)
w = np.matrix(w)
beta = (x.T * w * x).I * x.T * w * y
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
shapes (3,100) and (1,100) not aligned: 100 (dim 1) != 1 (dim 0)
import numpy as np
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
x = np.matrix(x)
y = np.matrix(y)
w = np.matrix(w)
beta = (x.T * w * x).I * x.T * w * y
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
shapes (3,100) and (1,100) not aligned: 100 (dim 1) != 1 (dim 0)
lipinski_rule_of_five
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
[insert]
return resultimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
result = True
if rdMolDescriptors.CalcNumHBD(mol) > 5:
result = False
if rdMolDescriptors.CalcNumHBA(mol) > 10:
result = False
if Descriptors.MolWt(mol) > 500:
result = False
if Crippen.MolLogP(mol) > 5:
result = False
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
result = True
if rdMolDescriptors.CalcNumHBD(mol) > 5:
result = False
if rdMolDescriptors.CalcNumHBA(mol) > 10:
result = False
if Descriptors.MolWt(mol) > 500:
result = False
if Crippen.MolLogP(mol) > 5:
result = False
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
result = True
if rdMolDescriptors.CalcNumHBD(mol) > 5:
result = False
if rdMolDescriptors.CalcNumHBA(mol) > 10:
result = False
if Descriptors.MolWt(mol) > 500:
result = False
if Crippen.MolLogP(mol) > 5:
result = False
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
result = True
if rdMolDescriptors.CalcNumHBD(mol) > 5:
result = False
if rdMolDescriptors.CalcNumHBA(mol) > 10:
result = False
if Descriptors.MolWt(mol) > 500:
result = False
if Crippen.MolLogP(mol) > 5:
result = False
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
result = True
if rdMolDescriptors.CalcNumHBD(mol) > 5:
result = False
if rdMolDescriptors.CalcNumHBA(mol) > 10:
result = False
if Descriptors.MolWt(mol) > 500:
result = False
if Crippen.MolLogP(mol) > 5:
result = False
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
Success
mape
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
[insert]
return eimport math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = 0
for i in range(len(y)):
e += abs(y_hat[i] - y[i]) / y[i]
e /= len(y)
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
Success
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = 0
for i in range(len(y)):
e += abs(y_hat[i]-y[i])/y[i]
e /= len(y)
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
Success
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = 0
for i in range(len(y)):
e += abs(y_hat[i] - y[i]) / y[i]
e /= len(y)
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
Success
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = 0
for i in range(len(y)):
e += abs(y_hat[i]-y[i])/y[i]
e /= len(y)
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
Success
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = 0
for i in range(len(y)):
e += abs((y[i]-y_hat[i])/y[i])
e = e/len(y)
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
Success
mapping_operator
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
[insert]
return Mimport MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((molecule.n_atoms, molecule.n_atoms))
for bead_idx, bead_mapping in enumerate(beads_mappings):
bead_mapping_idxs = molecule.select_atoms(bead_mapping).indices
M[bead_mapping_idxs, bead_mapping_idxs] = 1.0 / len(bead_mapping_idxs)
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
'list' object has no attribute 'replace'
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((len(beads_mappings), molecule.n_atoms))
for i, bead in enumerate(beads_mappings):
M[i, bead] = 1.0
M = np.dot(np.diag(molecule.masses), M)
M = np.dot(M, np.diag(1.0 / molecule.masses))
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((molecule.n_atoms, len(beads_mappings)))
for i, bead in enumerate(beads_mappings):
M[bead.indices, i] = bead.masses / bead.masses.sum()
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
'list' object has no attribute 'masses'
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((len(beads_mappings), molecule.n_atoms))
for i, beads_selection in enumerate(beads_mappings):
M[i,:] = np.sum(molecule.atoms.masses[beads_selection.indices])
M[i,:] /= np.sum(M[i,:])
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
'list' object has no attribute 'indices'
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((len(beads_mappings), molecule.n_atoms))
for i, bead in enumerate(beads_mappings):
M[i, bead.indices] = bead.masses / bead.masses.sum()
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
'list' object has no attribute 'masses'
matpow
import numpy as np
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
[insert]
return rimport numpy as np
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.eye(x.shape[0])
for i in range(n):
r = np.dot(r,x)
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.eye(x.shape[0])
for i in range(n):
r = np.dot(r,x)
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.eye(x.shape[0])
for i in range(n):
r = np.dot(r,x)
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.eye(len(x))
for i in range(n):
r = np.dot(r,x)
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.eye(x.shape[0])
for i in range(n):
r = np.dot(r,x)
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
matrix_factorial
import numpy as np
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
[insert]
return fimport numpy as np
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
f = np.zeros(n.shape)
for i in range(n.shape[0]):
for j in range(n.shape[1]):
f[i,j] = np.math.factorial(n[i,j])
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
Success
import numpy as np
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
f = np.zeros(n.shape)
for i in range(n.shape[0]):
for j in range(n.shape[1]):
f[i,j] = np.math.factorial(n[i,j])
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
Success
import numpy as np
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
f = np.ones(n.shape)
for i in range(n.shape[0]):
for j in range(n.shape[1]):
f[i,j] = np.math.factorial(n[i,j])
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
Success
import numpy as np
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
f = np.zeros(n.shape)
for i in range(n.shape[0]):
for j in range(n.shape[1]):
f[i,j] = np.math.factorial(n[i,j])
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
Success
import numpy as np
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
f = np.zeros(n.shape)
for i in range(n.shape[0]):
for j in range(n.shape[1]):
f[i,j] = np.math.factorial(n[i,j])
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
Success
max-boltz
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
[insert]
return simport math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.38064852e-23
s = math.sqrt(3*k*T/M)
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
Success
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.3806488e-23
s = math.sqrt(3*k*T/M)
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
Success
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.3806503e-23
s = math.sqrt(3*k*T/M)
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
Success
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.38064852e-23
s = math.sqrt(3*k*T/M)
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
Success
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.38064852e-23 # Boltzmann constant in J/K
s = math.sqrt(3*k*T/M)
s = s*1e3 # convert to m/s
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
Success
michaelis
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
[insert]
return v
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax*S/(Km+S)
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax*S/(Km+S)
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax*S/(Km+S)
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax * S / (Km + S)
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax*S/(Km+S)
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
mol_charge
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
[insert]
return chargeimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = Descriptors.MolWt(mol)
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = Descriptors.MolWt(mol)
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = Descriptors.MolWt(mol)
charge = round(charge, 2)
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = 0
for atom in mol.GetAtoms():
charge += atom.GetFormalCharge()
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = Descriptors.MolWt(mol)
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
net_charge
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
[insert]
return chargeimport math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for i in sequence:
if i == "K" or i == "R":
charge += 1
elif i == "D" or i == "E":
charge -= 1
else:
charge += 0
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
Success
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for i in sequence:
if i == 'K' or i == 'R':
charge += 1
elif i == 'D' or i == 'E':
charge -= 1
else:
charge += 0
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
Success
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for amino_acid in sequence:
if amino_acid == 'R' or amino_acid == 'K':
charge += 1
elif amino_acid == 'D' or amino_acid == 'E':
charge -= 1
else:
pass
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
Success
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for i in sequence:
if i == 'R' or i == 'K':
charge += 1
elif i == 'D' or i == 'E':
charge -= 1
else:
charge += 0
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
Success
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for aa in sequence:
if aa == 'K' or aa == 'R':
charge += 1
elif aa == 'D' or aa == 'E':
charge -= 1
else:
pass
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
Success
solve_ode
import numpy as np
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
[insert]
return solimport numpy as np
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
y = np.zeros((len(t), len(y0)))
y[0,:] = y0
for i in range(len(t)-1):
h = t[i+1]-t[i]
k1 = h*fn(t[i], y[i,:])
k2 = h*fn(t[i]+h/4, y[i,:]+k1/4)
k3 = h*fn(t[i]+3*h/8, y[i,:]+3*k1/32+9*k2/32)
k4 = h*fn(t[i]+12*h/13, y[i,:]+1932*k1/2197-7200*k2/2197+7296*k3/2197)
k5 = h*fn(t[i]+h, y[i,:]+439*k1/216-8*k2+3680*k3/513-845*k4/4104)
k6 = h*fn(t[i]+h/2, y[i,:]-8*k1/27+2*k2-3544*k3/2565+1859*k4/4104-11*k5/40)
y[i+1,:] = y[i,:] + 25*k1/216+1408*k3/2565+2197*k4/4104-k5/5
sol = y[:,0]
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
n = len(t)
y = np.zeros((n, len(y0)))
y[0] = y0
for i in range(n-1):
h = t[i+1] - t[i]
k1 = fn(t[i], y[i])
k2 = fn(t[i] + h/4, y[i] + h/4*k1)
k3 = fn(t[i] + 3*h/8, y[i] + 3*h/32*k1 + 9*h/32*k2)
k4 = fn(t[i] + 12*h/13, y[i] + 1932*h/2197*k1 - 7200*h/2197*k2 + 7296*h/2197*k3)
k5 = fn(t[i] + h, y[i] + 439*h/216*k1 - 8*h*k2 + 3680*h/513*k3 - 845*h/4104*k4)
k6 = fn(t[i] + h/2, y[i] - 8*h/27*k1 + 2*h*k2 - 3544*h/2565*k3 + 1859*h/4104*k4 - 11*h/40*k5)
y[i+1] = y[i] + h/6*(25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5)
sol = y
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
sol = np.zeros((len(t), len(y0)))
sol[0] = y0
for i in range(len(t)-1):
h = t[i+1] - t[i]
k1 = fn(t[i], sol[i])
k2 = fn(t[i] + h/4, sol[i] + h/4*k1)
k3 = fn(t[i] + 3*h/8, sol[i] + 3*h/32*k1 + 9*h/32*k2)
k4 = fn(t[i] + 12*h/13, sol[i] + 1932*h/2197*k1 - 7200*h/2197*k2 + 7296*h/2197*k3)
k5 = fn(t[i] + h, sol[i] + 439*h/216*k1 - 8*h*k2 + 3680*h/513*k3 - 845*h/4104*k4)
k6 = fn(t[i] + h/2, sol[i] - 8*h/27*k1 + 2*h*k2 - 3544*h/2565*k3 + 1859*h/4104*k4 - 11*h/40*k5)
sol[i+1] = sol[i] + h/6*(25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5)
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
n = len(t)
y = np.zeros((n, len(y0)))
y[0] = y0
for i in range(n-1):
h = t[i+1] - t[i]
k1 = fn(t[i], y[i])
k2 = fn(t[i] + h/4, y[i] + h/4*k1)
k3 = fn(t[i] + 3*h/8, y[i] + 3*h/32*k1 + 9*h/32*k2)
k4 = fn(t[i] + 12*h/13, y[i] + 1932*h/2197*k1 - 7200*h/2197*k2 + 7296*h/2197*k3)
k5 = fn(t[i] + h, y[i] + 439*h/216*k1 - 8*h*k2 + 3680*h/513*k3 - 845*h/4104*k4)
k6 = fn(t[i] + h/2, y[i] - 8*h/27*k1 + 2*h*k2 - 3544*h/2565*k3 + 1859*h/4104*k4 - 11*h/40*k5)
y[i+1] = y[i] + h/6*(25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5)
sol = y[:,0]
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
sol = np.zeros((len(t), len(y0)))
sol[0] = y0
for i in range(len(t)-1):
h = t[i+1] - t[i]
k1 = h*fn(t[i], sol[i])
k2 = h*fn(t[i] + h/4, sol[i] + k1/4)
k3 = h*fn(t[i] + 3*h/8, sol[i] + 3*k1/32 + 9*k2/32)
k4 = h*fn(t[i] + 12*h/13, sol[i] + 1932*k1/2197 - 7200*k2/2197 + 7296*k3/2197)
k5 = h*fn(t[i] + h, sol[i] + 439*k1/216 - 8*k2 + 3680*k3/513 - 845*k4/4104)
k6 = h*fn(t[i] + h/2, sol[i] - 8*k1/27 + 2*k2 - 3544*k3/2565 + 1859*k4/4104 - 11*k5/40)
sol[i+1] = sol[i] + 25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
ohe
import numpy as np
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
[insert]
return vimport numpy as np
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros((len(a), len(set(a))))
for i, k in enumerate(a):
v[i, k] = 1
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
import numpy as np
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros((len(a), len(set(a))))
for i, k in enumerate(a):
v[i, k] = 1
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
import numpy as np
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros((len(a), len(set(a))))
for i, x in enumerate(a):
v[i, x] = 1
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
import numpy as np
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros((len(a), len(np.unique(a))))
for i, k in enumerate(a):
v[i, k] = 1
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
import numpy as np
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros((len(a), len(set(a))))
for i, s in enumerate(a):
v[i, s] = 1
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
osmotic_pressure
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
[insert]
return pimport math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = Pi/(R*T)
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
Success
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = Pi/(R*T)
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
Success
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = Pi/(R*T)
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
Success
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = Pi/(R*T)
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
Success
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = Pi/(R*T)
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
Success
pair_wise
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
[insert]
return distancesimport mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
traj = md.load(pdb_file)
topology = traj.topology
alpha_carbons = topology.select('name CA')
distances = md.compute_distances(traj, alpha_carbons, alpha_carbons)
distances = distances[np.triu_indices(len(alpha_carbons), k=1)]
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
traj = md.load(pdb_file)
topology = traj.topology
alpha_carbons = topology.select('name CA')
distances = md.compute_distances(traj, alpha_carbons, periodic=False)
distances = np.tril(distances)
distances = distances[distances > 0]
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
traj = md.load(pdb_file)
alpha_carbons = traj.topology.select("name CA")
distances = md.compute_distances(traj, alpha_carbons, periodic=False)
distances = distances[0]
distances = np.triu(distances)
distances = distances[distances > 0]
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
traj = md.load(pdb_file)
alpha_carbons = traj.topology.select('name CA')
distances = md.compute_distances(traj, alpha_carbons, periodic=False)
distances = distances[0]
distances = distances[np.triu_indices(len(alpha_carbons), k=1)]
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
traj = md.load(pdb_file)
topology = traj.topology
alpha_carbons = topology.select('name CA')
distances = md.compute_distances(traj, alpha_carbons, periodic=False)
distances = distances[0]
distances = np.tril(distances)
distances = distances[distances != 0]
distances = distances.flatten()
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
pi
import numpy as np
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
[insert]
return pi_estimport numpy as np
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
x = np.random.uniform(-1,1,nsamples)
y = np.random.uniform(-1,1,nsamples)
r = np.sqrt(x**2+y**2)
pi_est = 4*np.sum(r<1)/nsamples
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
import numpy as np
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
x = np.random.uniform(0,1,nsamples)
y = np.random.uniform(0,1,nsamples)
pi_est = 4*np.sum(x**2 + y**2 < 1)/nsamples
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
import numpy as np
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
x = np.random.rand(nsamples)
y = np.random.rand(nsamples)
r = np.sqrt(x**2 + y**2)
pi_est = 4.0 * np.sum(r<1.0)/nsamples
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
import numpy as np
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
x = np.random.uniform(0,1,nsamples)
y = np.random.uniform(0,1,nsamples)
r = np.sqrt(x**2 + y**2)
pi_est = 4*np.sum(r<1)/nsamples
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
import numpy as np
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
x = np.random.uniform(-1, 1, nsamples)
y = np.random.uniform(-1, 1, nsamples)
r = np.sqrt(x**2 + y**2)
pi_est = 4.0 * np.sum(r < 1.0) / nsamples
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
pib_1d
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
[insert]
return eimport math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e = (n**2 * math.pi**2 * hbar**2)/(2*m*L**2)
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e = (hbar**2*n**2*math.pi**2)/(2*m*L**2)
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e = (n*n*math.pi*math.pi*hbar*hbar)/(2*m*L*L)
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e = (n*n*math.pi*math.pi*hbar*hbar)/(2*m*L*L)
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e = (n*n*math.pi*math.pi*hbar*hbar)/(2*m*L*L)
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
pred_interval
import numpy as np
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
[insert]
return nimport numpy as np
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = 1
while np.sum(p*(1-p)**np.arange(n)) < pred_level:
n += 1
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
Success
import numpy as np
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = 0
while (1 - p)**n < pred_level:
n += 1
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
Success
import numpy as np
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = 1
while np.power(1-p, n-1)*p < pred_level:
n += 1
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
Timeout
import numpy as np
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = np.ceil(np.log(1-pred_level)/np.log(1-p))
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
Success
import numpy as np
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = np.ceil(np.log(1-pred_level)/np.log(1-p))
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
Success
pubchem
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
[insert]
return molsimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/similarity/' + smiles + '/cids/TXT'
response = requests.get(url)
cids = response.text.split('\n')
cids = [x for x in cids if x]
cids = cids[:10]
mols = []
for cid in cids:
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/' + cid + '/property/CanonicalSMILES/TXT'
response = requests.get(url)
mols.append(response.text)
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/similarity/smiles/{}/cids/TXT?Threshold=80".format(smiles)
r = requests.get(url)
cids = r.text.split()
mols = set()
for cid in cids:
url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{}/property/CanonicalSMILES/TXT".format(cid)
r = requests.get(url)
mols.add(r.text)
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/similarity/smiles/' + smiles + '/cids/TXT?Threshold=80'
response = requests.get(url)
cids = response.text.split('\n')
cids = [cid for cid in cids if cid != '']
mols = []
for cid in cids:
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/' + cid + '/property/CanonicalSMILES/TXT'
response = requests.get(url)
mols.append(response.text)
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
'PropertyTable'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/similarity/smiles/{}/cids/TXT".format(smiles)
response = requests.get(url)
cids = response.text.split()
cids = cids[:10]
mols = []
for cid in cids:
url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{}/property/CanonicalSMILES/TXT".format(cid)
response = requests.get(url)
mols.append(response.text)
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/similarity/JSON'
params = {'smiles': smiles, 'threshold': 80, 'limit': 100}
r = requests.get(url, params=params)
mols = set()
for mol in r.json()['SimilarityList']:
mols.add(mol['CID'])
return mols
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
'SimilarityList'
pyscf_energy
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
[insert]
return ground_energyimport pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.Mole()
mol.atom = atom
mol.basis = basis
mol.build()
mf = pyscf.scf.RHF(mol)
mf.scf()
ground_energy = mf.e_tot
return ground_energy
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom,basis=basis)
mf = pyscf.scf.RHF(mol)
mf.kernel()
ground_energy = mf.e_tot
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.Mole()
mol.atom = atom
mol.basis = basis
mol.build()
mf = pyscf.scf.RHF(mol)
mf.scf()
ground_energy = mf.e_tot
print(ground_energy)
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.Mole()
mol.atom = atom
mol.basis = basis
mol.build()
mf = pyscf.scf.RHF(mol)
mf.kernel()
ground_energy = mf.e_tot
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom, basis=basis)
mf = pyscf.scf.RHF(mol)
mf.kernel()
ground_energy = mf.e_tot
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
qed
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
[insert]
return resultimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
result = Crippen.MolLogP(mol)
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
result = Crippen.MolLogP(mol)
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
result = Crippen.MolLogP(mol)
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
result = Crippen.MolLogP(mol)
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
result = Crippen.MolLogP(mol)
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
Success
quantile
import numpy as np
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
[insert]
return resultimport numpy as np
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
result = np.percentile(a, q * 100)
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
operands could not be broadcast together with shapes (300,) (3,)
import numpy as np
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
a = np.array(a)
result = []
for qq in q:
result.append(np.percentile(a, qq*100))
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
Success
import numpy as np
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
a = np.asarray(a)
m = np.arange(len(a))
g = np.c_[m, a]
g = g[g[:,1].argsort()]
g[:,0] = np.arange(len(a))
result = np.interp(q, g[:,0]/len(a), g[:,1])
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
Success
import numpy as np
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
a = np.array(a)
result = np.percentile(a, q*100)
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
operands could not be broadcast together with shapes (300,) (3,)
import numpy as np
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
a = np.asarray(a)
if a.ndim != 1:
raise ValueError("quantile() only works on 1D arrays")
if np.any(q < 0) or np.any(q > 1):
raise ValueError("quantiles must be between 0 and 1 inclusive")
result = np.empty(q.shape)
for i, qi in enumerate(q):
result[i] = np.percentile(a, qi * 100)
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
'<' not supported between instances of 'list' and 'int'
random_walk
import numpy as np
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
[insert]
return trajimport numpy as np
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = np.zeros(N)
for i in range(N):
traj[i] = x0
x0 += a*np.random.choice([-1,1])
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
Timeout
import numpy as np
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = np.zeros(N)
for i in range(N):
traj[i] = x0
x0 += a*np.random.choice([-1,1])
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
Timeout
import numpy as np
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = np.zeros(N)
traj[0] = x0
for i in range(1,N):
traj[i] = traj[i-1] + a*(np.random.randint(2)*2-1)
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
Success
import numpy as np
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = np.zeros(N)
for i in range(N):
traj[i] = x0 + a*np.random.choice([-1,1])
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
Timeout
import numpy as np
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = np.zeros(N)
for i in range(N):
traj[i] = x0
x0 += a*(2*np.random.randint(2)-1)
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
Success
rank
import numpy as np
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
[insert]
return rimport numpy as np
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M)
r = np.sum(s > 1e-12)
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
import numpy as np
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M)
r = np.sum(s > 1e-10)
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
import numpy as np
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, S, V = np.linalg.svd(M)
r = np.sum(S > 1e-6)
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
import numpy as np
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M)
r = np.sum(s > 1e-12)
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
import numpy as np
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M)
r = np.sum(s > 1e-12)
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
remove-water
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
[insert]
return new_trajimport mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
traj.remove_solvent()
new_traj = traj.atom_slice(traj.topology.select('not water'))
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
Success
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
top = traj.topology
new_traj = traj.atom_slice(top.select('not water'))
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
Success
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
top = traj.topology
new_traj = traj.atom_slice(top.select('not water'))
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
Success
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
top = traj.topology
new_traj = traj.atom_slice(np.where(top.residue(0).is_protein)[0])
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
Success
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
top = traj.topology
new_traj = traj.atom_slice(top.select('not water'))
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
Success
rms_velocity
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
[insert]
return v_rms
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38064852e-23 # Boltzmann constant in J/K
m = m * 1.6605e-27 # mass in kg
v_rms = math.sqrt(3*k*T/m)
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38064852e-23
m = m*1.660539040e-24
v_rms = math.sqrt(3*k*T/m)
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38064852e-23 # Boltzmann constant in J/K
m = m*1.6605e-27 # mass in kg
v_rms = math.sqrt(3*k*T/m)
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38064852e-23 # Boltzmann constant in J/K
m = m*1.66054e-24 # mass in g
v_rms = math.sqrt(3*k*T/m)
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38064852e-23 #J/K
m = m*1.66054e-24 #g to amu
v_rms = math.sqrt(3*k*T/m) #cm/s
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
rmse
import numpy as np
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
[insert]
return eimport numpy as np
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt(np.mean((a-b)**2))
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
Success
import numpy as np
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt(np.mean((a-b)**2))
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
Success
import numpy as np
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt(np.mean((a-b)**2))
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
Success
import numpy as np
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt(np.mean((a-b)**2))
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
Success
import numpy as np
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt(np.mean((a-b)**2))
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
Success
rog
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
[insert]
return rgimport mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
traj = md.load(pdb_file)
rg = md.compute_rg(traj)
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
traj = md.load(pdb_file)
rg = md.compute_rg(traj)
rg = np.mean(rg)
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
traj = md.load(pdb_file)
rg = md.compute_rg(traj)
rg = np.mean(rg)
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
traj = md.load(pdb_file)
rg = md.compute_rg(traj)
rg = np.mean(rg)
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
traj = md.load(pdb_file)
rg = md.compute_rg(traj)
rg = np.mean(rg)
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
sasa
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
[insert]
return sasaimport mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
traj = md.load(pdb_file)
sasa = md.shrake_rupley(traj)
sasa = np.sum(sasa, axis=1)
sasa = np.sum(sasa, axis=1)
sasa = np.sum(sasa, axis=1)
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
axis 1 is out of bounds for array of dimension 1
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
traj = md.load(pdb_file)
sasa = md.shrake_rupley(traj)
sasa = np.sum(sasa, axis=1)
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
Success
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
traj = md.load(pdb_file)
sasa = md.shrake_rupley(traj, mode='residue')
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
Success
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
traj = md.load(pdb_file)
sasa = md.shrake_rupley(traj, mode='residue')
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
Success
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
traj = md.load(pdb_file)
sasa = md.shrake_rupley(traj)
sasa = np.mean(sasa, axis=0)
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
Success
scaffold
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
[insert]
return scaffold_smilesimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
scaffold_smiles = Scaffolds.MurckoScaffoldSmiles(smiles)
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffoldSmiles'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
scaffold_smiles = Chem.MolToSmiles(Scaffolds.MurckoScaffoldSmiles(mol))
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffoldSmiles'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
scaffold_smiles = Scaffolds.MurckoScaffoldSmiles(smiles)
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffoldSmiles'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
scaffold_smiles = Chem.MolToSmiles(Scaffolds.MurckoScaffoldSmiles(mol))
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffoldSmiles'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
scaffold_smiles = Scaffolds.MurckoScaffoldSmiles(smiles)
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffoldSmiles'
seq-align
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
[insert]
return alignedfrom Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
aligned = pairwise2.format_alignment(*alns[0])
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
aligned = pairwise2.format_alignment(*alns[0])
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
aligned = pairwise2.format_alignment(*alns[0])
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
aligned = pairwise2.format_alignment(*alns[0])
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
aligned = [alns[0][0], alns[0][1]]
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
Success
seq-trans
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
[insert]
return prot_seqfrom Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq).translate()
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq).translate()
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq).translate()
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq).translate()
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = gene_seq.translate()
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
translate() takes exactly one argument (0 given)
sequence
import numpy as np
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
[insert]
return ximport numpy as np
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
x = np.geomspace(s,e,l)
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
Success
import numpy as np
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
x = np.zeros(l)
x[0] = s
for i in range(1,l):
x[i] = x[i-1]*e
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
Success
import numpy as np
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
x = np.logspace(np.log10(s),np.log10(e),l)
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
Success
import numpy as np
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
x = np.logspace(np.log10(s),np.log10(e),l)
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
Success
import numpy as np
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
x = np.geomspace(s,e,l)
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
Success
sle
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
[insert]
return ximport sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
x = sympy.solve(eqns)
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
x = sympy.solve(eqns)
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
x = sympy.solve(eqns)
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
x = sympy.solve(eqns)
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
x = sympy.solve(eqns)
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
spectral_r
import numpy as np
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
[insert]
return sradiusimport numpy as np
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
sradius = np.max(np.abs(np.linalg.eigvals(a)))
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
Success
import numpy as np
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
eigvals = np.linalg.eigvals(a)
sradius = np.max(np.abs(eigvals))
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
Success
import numpy as np
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
eigenvalues = np.linalg.eigvals(a)
sradius = np.max(np.abs(eigenvalues))
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
Success
import numpy as np
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
w, v = np.linalg.eig(a)
sradius = np.max(np.abs(w))
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
Success
import numpy as np
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
sradius = np.max(np.abs(np.linalg.eigvals(a)))
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
Success
find_peaks
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
[insert]
return wavenumbersimport numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
peaks, _ = scipy.signal.find_peaks(abs_spectrum[:, 1])
peaks = peaks[np.argsort(abs_spectrum[peaks, 1])][::-1]
peaks = peaks[:npeaks]
wavenumbers = abs_spectrum[peaks, 0]
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
Success
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
peaks, _ = scipy.signal.find_peaks(abs_spectrum[:, 1], height=0)
peaks = peaks[np.argsort(abs_spectrum[peaks, 1])[::-1]]
peaks = peaks[:npeaks]
wavenumbers = abs_spectrum[peaks, 0]
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
Success
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
peaks, _ = scipy.signal.find_peaks(abs_spectrum[:, 1], height=0.01)
peaks = peaks[np.argsort(abs_spectrum[peaks, 1])[::-1]]
wavenumbers = abs_spectrum[peaks, 0][:npeaks]
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
Success
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
peaks, _ = scipy.signal.find_peaks(abs_spectrum[:, 1], height=0.1)
peaks = peaks[np.argsort(abs_spectrum[peaks, 1])[::-1]]
wavenumbers = []
for peak in peaks[:npeaks]:
wavenumbers.append(abs_spectrum[peak, 0])
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
Success
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
wavenumbers = []
for i in range(npeaks):
peak_idx = np.argmax(abs_spectrum[:, 1])
peak_wavenumber = abs_spectrum[peak_idx, 0]
wavenumbers.append(peak_wavenumber)
abs_spectrum[peak_idx-10:peak_idx+10, 1] = 0
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
Success
speed_of_sound
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
[insert]
return s
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314 #J/mol/K
s = math.sqrt(gamma*R*T/m)
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314 #J/mol/K
s = math.sqrt(gamma*R*T/m)
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314
s = math.sqrt(gamma*R*T/m)
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314 #J/mol/K
s = math.sqrt(gamma*R*T/m)
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314
s = math.sqrt(gamma*R*T/m)
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
substructure
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
[insert]
return idximport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
idx = []
for i, mol in enumerate(mol_list):
if mol.HasSubstructMatch(Chem.MolFromSmiles(smiles)):
idx.append(i)
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
idx = []
for i in range(len(mol_list)):
if mol_list[i].HasSubstructMatch(Chem.MolFromSmiles(smiles)):
idx.append(i)
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
idx = []
for i in range(len(mol_list)):
if mol_list[i].HasSubstructMatch(Chem.MolFromSmiles(smiles)):
idx.append(i)
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
idx = []
for i, mol in enumerate(mol_list):
if mol.HasSubstructMatch(Chem.MolFromSmiles(smiles)):
idx.append(i)
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
idx = []
for i in range(len(mol_list)):
if mol_list[i].HasSubstructMatch(Chem.MolFromSmiles(smiles)):
idx.append(i)
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
tanimoto
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
[insert]
return simport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
mols = [Chem.MolFromSmiles(s) for s in smiles_list]
fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(m, 2, nBits=bits) for m in mols]
tanimoto_matrix = np.zeros((len(fps), len(fps)))
for i in range(len(fps)):
for j in range(i, len(fps)):
tanimoto_matrix[i, j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
tanimoto_matrix[j, i] = tanimoto_matrix[i, j]
return tanimoto_matrix
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
fps = [rdMolHash.GetMorganFingerprintAsBitVect(Chem.MolFromSmiles(s), bits) for s in smiles_list]
s = np.zeros((len(fps), len(fps)))
for i in range(len(fps)):
for j in range(i+1, len(fps)):
s[i,j] = s[j,i] = DataStructs.FingerprintSimilarity(fps[i], fps[j])
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
module 'rdkit.Chem.rdMolHash' has no attribute 'GetMorganFingerprintAsBitVect'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
mols = [Chem.MolFromSmiles(smiles) for smiles in smiles_list]
fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, 2, nBits=bits) for mol in mols]
tanimoto_matrix = np.zeros((len(fps), len(fps)))
for i in range(len(fps)):
for j in range(len(fps)):
tanimoto_matrix[i,j] = DataStructs.FingerprintSimilarity(fps[i], fps[j])
return tanimoto_matrix
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
mols = [Chem.MolFromSmiles(s) for s in smiles_list]
fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(m, 2, nBits=bits) for m in mols]
s = np.zeros((len(fps), len(fps)))
for i in range(len(fps)):
for j in range(len(fps)):
s[i,j] = DataStructs.FingerprintSimilarity(fps[i], fps[j])
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
mols = [Chem.MolFromSmiles(smi) for smi in smiles_list]
fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, 2, nBits=bits) for mol in mols]
tanimoto_matrix = np.zeros((len(fps), len(fps)))
for i in range(len(fps)):
for j in range(len(fps)):
tanimoto_matrix[i, j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
return tanimoto_matrix
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
Success
unbdistance
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
[insert]
return resultimport mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_com = md.compute_center_of_mass(traj.atom_slice(traj.top.select(lig_str)))
prot_com = md.compute_center_of_mass(traj.atom_slice(traj.top.select("protein")))
result = np.linalg.norm(lig_com - prot_com,axis=1)
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_ind = traj.topology.select('resname '+lig_str)
protein_ind = traj.topology.select('protein')
lig_com = md.compute_center_of_mass(traj.atom_slice(lig_ind))
protein_com = md.compute_center_of_mass(traj.atom_slice(protein_ind))
result = np.linalg.norm(lig_com-protein_com,axis=1)
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_res = traj.topology.select('resname '+lig_str)
lig_com = md.compute_center_of_mass(traj.atom_slice(lig_res))
prot_com = md.compute_center_of_mass(traj.atom_slice(traj.topology.select('protein')))
result = np.sqrt(np.sum((lig_com-prot_com)**2,axis=1))
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
top = traj.topology
lig_res = top.select('resname ' + lig_str)
prot_res = top.select('not resname ' + lig_str)
lig_com = md.compute_center_of_mass(traj.atom_slice(lig_res))
prot_com = md.compute_center_of_mass(traj.atom_slice(prot_res))
result = np.linalg.norm(lig_com - prot_com,axis=1)
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
top = traj.topology
lig_res = top.select('resname '+lig_str)
lig_com = md.compute_center_of_mass(traj.atom_slice(lig_res))
prot_com = md.compute_center_of_mass(traj.atom_slice(top.select('protein')))
result = np.linalg.norm(lig_com-prot_com,axis=1)
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here ## Test Report ### Global Parameters * Engine = openai/code-cushman-001 * T = 0.2
| Test | Run 0 | Run 1 | Run 2 | Run 3 | Run 4 |
|---|---|---|---|---|---|
| aa_polarity | Pass | Fail | Fail | Fail | Fail |
| adiabatic_expansion | Pass | Pass | Pass | Pass | Pass |
| alignment | Fail | Fail | Fail | Fail | Fail |
| angle | Pass | Pass | Fail | Pass | Pass |
| aromatic_aa | Pass | Pass | Pass | Pass | Pass |
| arrhenius | Pass | Pass | Pass | Fail | Pass |
| bimolecular | Pass | Pass | Pass | Pass | Pass |
| bb_rad | Pass | Pass | Pass | Pass | Pass |
| blast | Fail | Fail | Fail | Fail | Fail |
| bravais | Fail | Pass | Fail | Fail | Fail |
| canonicalize | Pass | Pass | Pass | Pass | Pass |
| carnot_efficiency | Pass | Pass | Pass | Pass | Pass |
| claussius | Fail | Pass | Pass | Pass | Pass |
| compare_electronegativity | Fail | Fail | Fail | Fail | Fail |
| condiff_1d | Pass | Pass | Pass | Pass | Pass |
| cubes | Fail | Pass | Pass | Pass | Pass |
| de_broglie | Pass | Pass | Pass | Pass | Pass |
| derivative1d-ch | Pass | Pass | Pass | Pass | Pass |
| derivative_2deg | Pass | Pass | Pass | Pass | Pass |
| descriptors | Fail | Fail | Fail | Fail | Fail |
| dipole | Pass | Pass | Fail | Pass | Pass |
| dou | Fail | Fail | Fail | Fail | Fail |
| eigen-ch | Pass | Pass | Pass | Pass | Pass |
| eigen | Pass | Pass | Pass | Pass | Pass |
| element_mass | Pass | Pass | Pass | Pass | Pass |
| element_name | Pass | Pass | Pass | Pass | Pass |
| energy_of_e | Pass | Pass | Fail | Fail | Pass |
| find_indices | Fail | Fail | Fail | Fail | Fail |
| force_constant | Fail | Fail | Fail | Fail | Fail |
| fourier_1d | Pass | Fail | Pass | Fail | Pass |
| freezing_depression | Pass | Pass | Pass | Pass | Pass |
| genpos | Fail | Fail | Fail | Fail | Fail |
| heating_water | Fail | Fail | Fail | Fail | Fail |
| hydrophobic_res | Fail | Fail | Fail | Fail | Fail |
| ideal_gas | Pass | Pass | Pass | Pass | Pass |
| integral | Fail | Fail | Fail | Fail | Fail |
| trap | Pass | Pass | Pass | Pass | Pass |
| invert_matrix | Fail | Pass | Fail | Fail | Pass |
| iupac2smiles | Fail | Fail | Fail | Fail | Fail |
| kld | Fail | Fail | Fail | Fail | Fail |
| langevin_dynamics | Fail | Fail | Fail | Fail | Pass |
| weighted-least-squares | Fail | Pass | Fail | Fail | Fail |
| lipinski_rule_of_five | Pass | Pass | Fail | Pass | Pass |
| mape | Fail | Fail | Fail | Fail | Fail |
| mapping_operator | Fail | Fail | Fail | Fail | Fail |
| matpow | Fail | Fail | Fail | Fail | Pass |
| matrix_factorial | Fail | Fail | Fail | Fail | Fail |
| max-boltz | Pass | Pass | Fail | Fail | Fail |
| michaelis | Pass | Pass | Pass | Pass | Pass |
| mol_charge | Pass | Fail | Pass | Fail | Pass |
| net_charge | Pass | Pass | Pass | Pass | Pass |
| solve_ode | Fail | Fail | Fail | Fail | Fail |
| ohe | Fail | Fail | Fail | Fail | Fail |
| osmotic_pressure | Pass | Pass | Pass | Pass | Pass |
| pair_wise | Fail | Fail | Fail | Fail | Fail |
| pi | Pass | Pass | Pass | Pass | Pass |
| pib_1d | Pass | Pass | Pass | Pass | Pass |
| pred_interval | Pass | Pass | Pass | Pass | Pass |
| pubchem | Fail | Fail | Fail | Fail | Fail |
| pyscf_energy | Fail | Fail | Fail | Fail | Fail |
| qed | Pass | Pass | Pass | Pass | Pass |
| quantile | Fail | Pass | Fail | Fail | Fail |
| random_walk | Pass | Pass | Pass | Pass | Pass |
| rank | Pass | Pass | Pass | Pass | Pass |
| remove-water | Fail | Fail | Pass | Pass | Pass |
| rms_velocity | Fail | Fail | Fail | Fail | Fail |
| rmse | Pass | Pass | Pass | Pass | Pass |
| rog | Pass | Pass | Pass | Pass | Pass |
| sasa | Fail | Fail | Fail | Fail | Fail |
| scaffold | Fail | Fail | Fail | Fail | Fail |
| seq-align | Pass | Pass | Pass | Fail | Pass |
| seq-trans | Pass | Pass | Pass | Pass | Pass |
| sequence | Fail | Fail | Fail | Pass | Fail |
| sle | Fail | Fail | Fail | Fail | Fail |
| spectral_r | Fail | Pass | Pass | Fail | Fail |
| find_peaks | Fail | Fail | Fail | Fail | Fail |
| speed_of_sound | Fail | Fail | Fail | Fail | Fail |
| substructure | Fail | Fail | Fail | Fail | Fail |
| tanimoto | Pass | Pass | Pass | Fail | Pass |
| unbdistance | Fail | Fail | Fail | Fail | Fail |
aa_polarity
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
polar_count = 0
for aa in sequence:
if aa in ['S', 'T', 'N', 'Q', 'C', 'M']:
polar_count += 1
return polar_count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
polar = ['S', 'T', 'N', 'Q', 'H', 'K', 'R', 'D', 'E']
count = 0
for aa in sequence:
if aa in polar:
count += 1
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
polar_count = 0
for amino_acid in sequence:
if amino_acid in ["G", "A", "S", "T", "C", "P"]:
polar_count += 1
return polar_count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
polar_count = 0
for aa in sequence:
if aa in ['R', 'K', 'D', 'E', 'Q', 'N', 'H', 'S', 'T', 'Y', 'C', 'M', 'W']:
polar_count += 1
return polar_count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
polar_count = 0
for aa in sequence:
if aa in ['R', 'K', 'N', 'Q', 'H', 'S', 'T', 'Y', 'C', 'M', 'W']:
polar_count += 1
return polar_count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
adiabatic_expansion
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1 * (P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1*(P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1*(P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1*(P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1*(P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
alignment
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
# align to the first frame
traj.superpose(traj, frame=frame_index)
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
'NoneType' object has no attribute 'xyz'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
# align to the first frame
traj.superpose(traj, frame=frame_index)
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
'NoneType' object has no attribute 'xyz'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
# align to the frame
traj.superpose(traj, frame=frame_index)
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
'NoneType' object has no attribute 'xyz'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
# align to first frame
traj.superpose(traj, frame=frame_index)
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
'NoneType' object has no attribute 'xyz'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
# align to the first frame
traj.superpose(traj, frame=frame_index)
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
'NoneType' object has no attribute 'xyz'
angle
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
# start
v1_u = v1 / np.linalg.norm(v1)
v2_u = v2 / np.linalg.norm(v2)
return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
# start
v1_u = v1/np.linalg.norm(v1)
v2_u = v2/np.linalg.norm(v2)
return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
# start
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
# start
v1_u = v1 / np.linalg.norm(v1)
v2_u = v2 / np.linalg.norm(v2)
return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
# start
v1_norm = np.linalg.norm(v1)
v2_norm = np.linalg.norm(v2)
cos_angle = np.dot(v1,v2) / (v1_norm * v2_norm)
angle = np.arccos(cos_angle)
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
aromatic_aa
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
aromatic_residues = ['F', 'Y', 'W']
aromatic_count = 0
for aa in sequence:
if aa in aromatic_residues:
aromatic_count += 1
return aromatic_count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
aromatic_residues = ['F', 'Y', 'W']
aromatic_count = 0
for aa in sequence:
if aa in aromatic_residues:
aromatic_count += 1
return aromatic_count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
aromatic_residues = ['F', 'Y', 'W']
aromatic_count = 0
for aa in sequence:
if aa in aromatic_residues:
aromatic_count += 1
return aromatic_count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
aromatic = 0
for aa in sequence:
if aa == 'F' or aa == 'Y' or aa == 'W':
aromatic += 1
return aromatic
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
aromatic_count = 0
for aa in sequence:
if aa in ['F', 'Y', 'W']:
aromatic_count += 1
return aromatic_count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
arrhenius
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
R = 8.314 #J/mol/K
k1 = k2 * math.exp((Ea/R)*((1/T2)-(1/T1)))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = k2 * math.exp((Ea/8.314) * (1/T2 - 1/T1))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = k2 * math.exp((Ea/8.314)*((1/T2)-(1/T1)))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = k2 * math.exp((Ea/8.314)*((1/T1)-(1/T2)))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = k2 * math.exp((-Ea/8.314)*((1/T1)-(1/T2)))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
bimolecular
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
return k*A*B
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
return k*A*B
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
return k*A*B
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
return k*A*B
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
return k*A*B
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
bb_rad
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
h = 6.626e-34
c = 3e8
k = 1.38e-23
return 2*h*c**2/lam**5/(np.exp(h*c/(lam*k*T))-1)
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
h = 6.626e-34
c = 3.0e+8
k = 1.38e-23
return (2*h*c**2/lam**5)*(1/(np.exp(h*c/(lam*k*T))-1))
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
h = 6.626e-34
c = 3.0e+8
k = 1.38e-23
return 2*h*c**2/lam**5/(np.exp(h*c/(lam*k*T))-1)
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
h = 6.626e-34
c = 3e8
k = 1.38e-23
return 2*h*c**2/lam**5/(np.exp(h*c/(lam*k*T))-1)
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
c = 3e8
h = 6.626e-34
k = 1.38e-23
return 2*h*c**2/(lam**5*(np.exp(h*c/(lam*k*T))-1))
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
blast
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1. import packages
import requests
from bs4 import BeautifulSoup
import numpy as np
# 2. Submit BLAST search with sequences
url = 'https://blast.ncbi.nlm.nih.gov/Blast.cgi'
data = {
'QUERY': seq,
'DATABASE': 'nr',
'PROGRAM': 'blastp',
'FILTER': 'L',
'EXPECT': '1e-5',
'HITLIST_SIZE': '1',
'ALIGNMENTS': '1',
'ALIGNMENT_VIEW': 'Tabular',
'DESCRIPTIONS': '1',
'FORMAT_TYPE': 'HTML',
'NCBI_GI': 'on',
'CLIENT': 'web',
'SERVICE': 'plain',
'CMD': 'Put'
}
# 3. Get result
r = requests.post(url, data=data)
soup = BeautifulSoup(r.text, 'html.parser')
#print(soup.prettify())
# 4. Parse MSA
# get the alignment
align = soup.find_all('pre')[0].text
#print(align)
# split the alignment into lines
align = align.split('\n')
#print(align)
# get the query sequence
query = align[0].split()[1]
#print(query)
# get the top hit
top_hit = align[1].split()[1]
#print(top_hit)
# get the e score
e_score = align[2].split()[2]
#print(e_score)
# 5. Return a tuple of e score, id of top match
return (e_score, top_hit)
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
list index out of range
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1. import packages
import requests
from bs4 import BeautifulSoup
import numpy as np
# 2. Submit BLAST search with sequences
url = "http://www.uniprot.org/blast/"
headers = {'content-type': 'application/x-www-form-urlencoded'}
payload = {'query': seq, 'database': 'swissprot', 'format': 'html', 'align': 'yes'}
r = requests.post(url, data=payload, headers=headers)
# 3. Get result
soup = BeautifulSoup(r.text, 'html.parser')
# 4. Parse MSA
msa = soup.find_all('pre')[0].text
msa = msa.split('\n')
msa = [line for line in msa if line.startswith('>')]
msa = [line.split('|')[1] for line in msa]
msa = [line.split(' ')[0] for line in msa]
msa = [line for line in msa if line != '']
# 5. Return a tuple of e score, id of top match
return msa
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
list index out of range
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1. import packages
import requests
from bs4 import BeautifulSoup
import numpy as np
# 2. Submit BLAST search with sequences
# 2.1. Create a dictionary with the sequences
seq_dict = {'sequence': seq}
# 2.2. Submit the search
r = requests.post('http://blast.ncbi.nlm.nih.gov/Blast.cgi', data=seq_dict)
# 2.3. Get the result
result = r.text
# 3. Parse MSA
soup = BeautifulSoup(result, 'html.parser')
# 3.1. Get the MSA
msa = soup.find_all('pre')[0].text
# 3.2. Get the e score
e_score = soup.find_all('td')[-1].text
# 3.3. Get the id of the top match
top_match = soup.find_all('td')[-2].text
# 4. Return a tuple of e score, id of top match
return e_score, top_match, msa
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
list index out of range
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1. import packages
import requests
from bs4 import BeautifulSoup
import numpy as np
# 2. Submit BLAST search with sequences
url = 'http://blast.ncbi.nlm.nih.gov/Blast.cgi'
params = {'QUERY': seq,
'DATABASE': 'nr',
'PROGRAM': 'blastp',
'FILTER': 'L',
'EXPECT': '1e-3',
'HITLIST_SIZE': '1',
'ALIGNMENTS': '50',
'DESCRIPTIONS': '50',
'FORMAT_TYPE': 'HTML',
'NCBI_GI': 'on',
'CMD': 'Put'}
# 3. Get result
r = requests.get(url, params=params)
soup = BeautifulSoup(r.text, 'html.parser')
# 4. Parse MSA
alignments = soup.find_all('pre')[1].text
alignments = alignments.split('\n')
alignments = [x for x in alignments if x != '']
alignments = [x for x in alignments if x[0] != '>']
alignments = [x for x in alignments if x[0] != ' ']
alignments = [x for x in alignments if x[0] != '\n']
alignments = [x for x in alignments if x[0] != '\r']
alignments = [x for x in alignments if x[0] != '\t']
alignments = [x for x in alignments if x[0] != '\f']
alignments = [x for x in alignments if x[0] != '\v']
alignments = [x for x in alignments if x[0] != '\b']
alignments = [x for x in alignments if x[0] != '\a']
alignments = [x for x in alignments if x[0] != '\0']
alignments = [x for x in alignments if x[0] != '\1']
alignments = [x for x in alignments if x[0] != '\2']
alignments = [x for x in alignments if x[0] != '\3']
alignments = [x for x in alignments if x[0] != '\4']
alignments = [x for x in alignments if x[0] != '\5']
alignments = [x for x in alignments if x[0] != '\6']
alignments = [x for x in alignments if x[0] != '\7']
alignments = [x for x in alignments if x[0] != '\8']
alignments = [x for x in alignments if x[0] != '\9']
alignments = [x for x in alignments if x[0] != '\10']
alignments = [x for x in alignments if x[0] != '\11']
alignments = [x for x in alignments if x[0] != '\12']
alignments = [x for x in alignments if x[0] != '\13']
alignments = [x for x in alignments if x[0] != '\14']
alignments = [x for x in alignments if x[0] != '\15']
alignments = [x for x in alignments if x[0] != '\16']
alignments = [x for x in alignments if x[0] != '\17']
alignments = [x for x in alignments if x[0] != '\18']
alignments = [x
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
invalid syntax (<string>, line 79)
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1. import packages
import requests
from bs4 import BeautifulSoup
import numpy as np
# 2. Submit BLAST search with sequences
url = 'http://www.ebi.ac.uk/Tools/services/rest/emboss_needle/run/'
seq = '>seq1\n' + seq + '\n'
seq += '>seq2\n' + seq + '\n'
seq += '>seq3\n' + seq + '\n'
seq += '>seq4\n' + seq + '\n'
seq += '>seq5\n' + seq + '\n'
seq += '>seq6\n' + seq + '\n'
seq += '>seq7\n' + seq + '\n'
seq += '>seq8\n' + seq + '\n'
seq += '>seq9\n' + seq + '\n'
seq += '>seq10\n' + seq + '\n'
seq += '>seq11\n' + seq + '\n'
seq += '>seq12\n' + seq + '\n'
seq += '>seq13\n' + seq + '\n'
seq += '>seq14\n' + seq + '\n'
seq += '>seq15\n' + seq + '\n'
seq += '>seq16\n' + seq + '\n'
seq += '>seq17\n' + seq + '\n'
seq += '>seq18\n' + seq + '\n'
seq += '>seq19\n' + seq + '\n'
seq += '>seq20\n' + seq + '\n'
seq += '>seq21\n' + seq + '\n'
seq += '>seq22\n' + seq + '\n'
seq += '>seq23\n' + seq + '\n'
seq += '>seq24\n' + seq + '\n'
seq += '>seq25\n' + seq + '\n'
seq += '>seq26\n' + seq + '\n'
seq += '>seq27\n' + seq + '\n'
seq += '>seq28\n' + seq + '\n'
seq += '>seq29\n' + seq + '\n'
seq += '>seq30\n' + seq + '\n'
seq += '>seq31\n' + seq + '\n'
seq += '>seq32\n' + seq + '\n'
seq += '>seq33\n' + seq + '\n'
seq += '>seq34\n' + seq + '\n'
seq += '>seq35\n' + seq + '\n'
seq += '>seq36\n' + seq + '\n'
seq += '>seq37\n' + seq + '\n'
seq += '>seq38\n' + seq + '\n'
seq += '>seq39\n' + seq + '\n'
seq += '>seq40\n' + seq + '\n'
seq += '>seq41\n' + seq + '\n'
seq += '>seq42\n' + seq + '\n'
seq += '>seq43\n' + seq + '\n'
seq += '>seq44\n' + seq + '\n'
seq += '>seq45\n' + seq + '\n'
seq += '>seq46\n' + seq + '\n
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
EOL while scanning string literal (<string>, line 75)
bravais
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
if group_number in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
invalid syntax (<string>, line 17)
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
if group_number in range(1, 3):
return "triclinic"
elif group_number in range(3, 16):
return "monoclinic"
elif group_number in range(16, 75):
return "orthorhombic"
elif group_number in range(75, 143):
return "tetragonal"
elif group_number in range(143, 168):
return "trigonal"
elif group_number in range(168, 195):
return "hexagonal"
elif group_number in range(195, 231):
return "cubic"
else:
return "unknown"
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
return bravais_lattice_name[group_number]
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
name 'bravais_lattice_name' is not defined
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
if group_number in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
invalid syntax (<string>, line 17)
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
if group_number in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
invalid syntax (<string>, line 17)
canonicalize
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canonical_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canonical_list.append(Chem.MolToSmiles(mol, isomericSmiles=True))
return canonical_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canonical_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canonical_list.append(Chem.MolToSmiles(mol))
return canonical_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
smiles_canonical = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
smiles_canonical.append(Chem.MolToSmiles(mol, isomericSmiles=True))
return smiles_canonical
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canonical_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canonical_list.append(Chem.MolToSmiles(mol, isomericSmiles=True))
return canonical_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
can_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
can_list.append(Chem.MolToSmiles(mol, isomericSmiles=True))
return can_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
carnot_efficiency
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
return 1 - T_cold / T_hot
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
return 1 - T_cold / T_hot
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
return 1 - T_cold / T_hot
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
return 1 - T_cold / T_hot
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
return 1 - T_cold / T_hot
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
claussius
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = P1 * math.exp(HVap * (1 / T1 - 1 / T2))
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
return P1 * math.exp(HVap * (1 / T1 - 1 / T2) / 8.314)
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
return P1 * math.exp((HVap / 8.314) * (1 / T1 - 1 / T2))
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
return P1 * math.exp((HVap / 8.314) * (1 / T1 - 1 / T2))
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
return P1 * math.exp(HVap * (1 / T1 - 1 / T2) / 8.314)
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
compare_electronegativity
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
if mendeleev.element(element1).pauling > mendeleev.element(element2).pauling:
return True
else:
return False
result = True if compare_electronegativity("O","C") else FalseOutput:
'Element' object has no attribute 'pauling'
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
if mendeleev.element(element1).pauling_electronegativity > mendeleev.element(element2).pauling_electronegativity:
return True
else:
return False
result = True if compare_electronegativity("O","C") else FalseOutput:
'Element' object has no attribute 'pauling_electronegativity'
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
if mendeleev.element(element1).pauling_en > mendeleev.element(element2).pauling_en:
return True
else:
return False
result = True if compare_electronegativity("O","C") else FalseOutput:
'Element' object has no attribute 'pauling_en'
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
if mendeleev.element(element1).pauling_en > mendeleev.element(element2).pauling_en:
return True
else:
return False
result = True if compare_electronegativity("O","C") else FalseOutput:
'Element' object has no attribute 'pauling_en'
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
e1 = mendeleev.element(element1)
e2 = mendeleev.element(element2)
if e1.electronegativity > e2.electronegativity:
return True
else:
return False
result = True if compare_electronegativity("O","C") else FalseOutput:
'>' not supported between instances of 'method' and 'method'
condiff_1d
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
return np.diff(x)
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
# start
return x[1:] - x[:-1]
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
return x[1:] - x[:-1]
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.zeros(len(x)-1)
for i in range(len(x)-1):
diff[i] = x[i+1] - x[i]
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
return np.diff(x)
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
cubes
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
sum = 0
for i in range(n):
sum += i**3
return sum
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
sum = 0
for i in range(1, n + 1):
sum += i * i * i
return sum
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
sum = 0
for i in range(1, n+1):
sum += i**3
return sum
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
sum = 0
for i in range(1, n + 1):
sum += i ** 3
return sum
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
sum = 0
for i in range(1, n + 1):
sum += i ** 3
return sum
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
de_broglie
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
h = 6.62606896e-34
c = 299792458.0
return h / (m * v)
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
h = 6.626e-34
return h / (m * v)
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
h = 6.626e-34
return h / (m * v)
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
h = 6.626068e-34
c = 3.0e+8
return h / (m * v * c)
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
h = 6.626068e-34
c = 3.0e+8
return h / (m * v * c)
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
derivative1d-ch
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
return 2*a*x + b
"""
Create a function that returns the derivative of a second order polynomial
"""
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
return 2*a*x + b
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
# start
return 2*a*x + b
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
y = a*x**2 + b*x + c
return 2*a*x + b
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
# start
return 2*a*x + b
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
derivative_2deg
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
return 2*a*x + b
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
return 2*a*x + b
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
return 2*a*x + b
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
return 2*a*x + b
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
return 2*a*x + b
"""
Create a matrix of zeros
"""
a = np.zeros((5,10))
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
descriptors
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
nms = [x[0] for x in Descriptors._descList]
calc = MoleculeDescriptors.MolecularDescriptorCalculator(nms)
descriptors = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
descriptors.append(calc.CalcDescriptors(mol))
return np.array(descriptors)
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
nms = [x[0] for x in Descriptors._descList]
calc = MoleculeDescriptors.MolecularDescriptorCalculator(nms)
descriptors = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
descrs = calc.CalcDescriptors(mol)
descriptors.append(descrs)
return np.array(descriptors)
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
nms = [x[0] for x in Descriptors._descList]
calc = MoleculeDescriptors.MolecularDescriptorCalculator(nms)
descriptors = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
if mol:
descrs = calc.CalcDescriptors(mol)
descriptors.append(descrs)
else:
print("Could not parse SMILES string:", smiles)
return np.array(descriptors)
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
nms = [x[0] for x in Descriptors._descList]
calc = MoleculeDescriptors.MolecularDescriptorCalculator(nms)
desc_list = []
for smiles in smiles_list:
m = Chem.MolFromSmiles(smiles)
desc_list.append(calc.CalcDescriptors(m))
return np.array(desc_list)
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
# initialize the descriptor calculator
calc = MoleculeDescriptors.MolecularDescriptorCalculator([
'MolWt',
'MolLogP',
'TPSA',
'LabuteASA',
'NumRotatableBonds',
'NumHDonors',
'NumHAcceptors',
'NumHeteroatoms',
'NumAromaticRings',
'NumSaturatedRings',
'NumAliphaticRings',
'NumAromaticHeterocycles',
'NumSaturatedHeterocycles',
'NumAliphaticHeterocycles',
'NumAromaticCarbocycles',
'NumSaturatedCarbocycles',
'NumAliphaticCarbocycles',
'NumAromaticRings',
'NumSaturatedRings',
'NumAliphaticRings',
'NumAromaticHeterocycles',
'NumSaturatedHeterocycles',
'NumAliphaticHeterocycles',
'NumAromaticCarbocycles',
'NumSaturatedCarbocycles',
'NumAliphaticCarbocycles',
'NumHeterocycles',
'NumRings',
'NumAmideBonds',
'NumLipinskiHBA',
'NumLipinskiHBD',
'NumLipinskiRO5Violations',
'NumRotatableBonds',
'NumHBA',
'NumHBD',
'NumHeteroatoms',
'NumHeterocycles',
'NumRings',
'NumRotatableBonds',
'NumSaturatedCarbocycles',
'NumSaturatedHeterocycles',
'NumSaturatedRings',
'NumSpiroAtoms',
'NumBridgeheadAtoms',
'NumHBA',
'NumHBD',
'NumHeteroatoms',
'NumHeterocycles',
'NumRings',
'NumRotatableBonds',
'NumSaturatedCarbocycles',
'NumSaturatedHeterocycles',
'NumSaturatedRings',
'NumSpiroAtoms',
'NumBridgeheadAtoms',
'NumHBA',
'NumHBD',
'NumHeteroatoms',
'NumHeterocycles',
'NumRings',
'NumRotatableBonds',
'NumSaturatedCarbocycles',
'NumSaturatedHeterocycles',
'NumSaturatedRings',
'NumSpiroAtoms',
'NumBridgeheadAtoms',
'NumHBA',
'NumHBD',
'NumHeteroatoms',
'NumHeterocycles',
'NumRings',
'NumRotatableBonds',
'NumSaturatedCarbocycles',
'NumSaturatedHeterocycles',
'NumSaturatedRings',
'NumSpiroAtoms',
'NumBridgeheadAtoms',
'NumHBA',
'NumHBD',
'NumHeteroatoms',
'NumHeterocycles',
'NumRings',
'NumRotatableBonds',
'NumSaturatedCarbocycles',
'NumSaturatedHeterocycles',
'NumSaturatedRings',
'NumSpiroAtoms',
'NumBridgeheadAtoms',
'NumHBA',
'NumHBD',
'NumHeteroatoms',
'NumHeterocycles',
'NumRings',
'NumRotatableBonds',
'NumSaturatedCarb
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
EOL while scanning string literal (<string>, line 122)
dipole
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole = np.zeros(3)
for i in range(len(charges)):
dipole += charges[i] * coordinates[i]
return dipole
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole = np.zeros(3)
for i in range(len(charges)):
dipole += charges[i]*coordinates[i]
return dipole
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
# start
dipole = np.sum(coordinates * charges[:, np.newaxis], axis=0)
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
unsupported operand type(s) for -: 'float' and 'NoneType'
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole = np.zeros(3)
for i in range(len(charges)):
dipole += charges[i] * coordinates[i]
return dipole
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
return np.sum(coordinates * charges[:, np.newaxis], axis=0)
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
Success
dou
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return None
else:
return rdMolDescriptors.CalcNumLipinskiHBA(mol), rdMolDescriptors.CalcNumLipinskiHBD(mol)
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
c = mol.GetNumAtoms()
n = 0
h = 0
hal = 0
for atom in mol.GetAtoms():
if atom.GetAtomicNum() == 7:
n += 1
elif atom.GetAtomicNum() == 1:
h += 1
elif atom.GetAtomicNum() == 9:
hal += 1
elif atom.GetAtomicNum() == 17:
hal += 1
elif atom.GetAtomicNum() == 35:
hal += 1
elif atom.GetAtomicNum() == 53:
hal += 1
rdb = (2*(c-n-h-hal)+n+hal)/2
return rdb
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
C = rdMolDescriptors.CalcNumAtomStereoCenters(mol)
N = rdMolDescriptors.CalcNumAmideBonds(mol)
H = rdMolDescriptors.CalcNumHBD(mol)
Halogen = rdMolDescriptors.CalcNumHeteroatoms(mol)
rdbs = (C + N + H + Halogen)
return rdbs
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
rdb = Descriptors.NumRadicalElectrons(mol)
return rdb
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
rdbs = Descriptors.NumRadicalElectrons(mol)
return rdbs
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
Success
eigen-ch
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
# start
eig_values, eig_vectors = np.linalg.eig(M)
return eig_values, eig_vectors
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
# start
eigen_values, eigen_vectors = np.linalg.eig(M)
return eigen_values, eigen_vectors
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
# start
eigen_values, eigen_vectors = np.linalg.eig(M)
return eigen_values, eigen_vectors
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
# start
eigenvalues, eigenvectors = np.linalg.eig(M)
return eigenvalues, eigenvectors
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
# start
eig_val, eig_vec = np.linalg.eig(M)
return eig_val, eig_vec
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
eigen
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
return np.linalg.eig(M)
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
# start
eigvals, eigvecs = np.linalg.eig(M)
return eigvals, eigvecs
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
eigval, eigvec = np.linalg.eig(M)
return eigval, eigvec
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
return np.linalg.eig(M)
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
return np.linalg.eig(M)
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
element_mass
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
element = mendeleev.element(element_symbol)
return element.mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
return mendeleev.element(element_symbol).mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
element = mendeleev.element(element_symbol)
return element.mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
return mendeleev.element(element_symbol).mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
return mendeleev.element(element_symbol).mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
Success
element_name
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
return mendeleev.element(element_number).symbol
result = True if symbol(26).lower()=="fe" else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
element = mendeleev.element(element_number)
return element.symbol
result = True if symbol(26).lower()=="fe" else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
return mendeleev.element(element_number).symbol
result = True if symbol(26).lower()=="fe" else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
return mendeleev.element(element_number).symbol
result = True if symbol(26).lower()=="fe" else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
return mendeleev.element(element_number).symbol
result = True if symbol(26).lower()=="fe" else FalseOutput:
Success
energy_of_e
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
return -13.6 * (1 / (n ** 2))
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
return -13.6 * (1 / (n ** 2))
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
# start
e = -13.6 * (1 / (n ** 2))
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
must be real number, not NoneType
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
# start
energy = -13.6 * (1 / (n ** 2))
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
must be real number, not NoneType
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
return -13.6 * (1 / (n ** 2))
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
find_indices
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
traj = md.load(pdb_file)
topology = traj.topology
atom_indices = topology.select('name CA')
return atom_indices[0], atom_indices[1]
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
pdb = md.load_pdb(pdb_file)
ca_indices = []
for atom in pdb.topology.atoms:
if atom.name == 'CA':
ca_indices.append(atom.index)
return ca_indices
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
traj = md.load(pdb_file)
topology = traj.topology
ca_indices = topology.select('name CA')
return ca_indices[0], ca_indices[1]
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
t = md.load(pdb_file)
topology = t.topology
ca_indices = topology.select('name CA')
return ca_indices[0], ca_indices[1]
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
pdb = md.load_pdb(pdb_file)
ca_indices = []
for i in range(pdb.n_atoms):
if pdb.topology.atom(i).name == 'CA':
ca_indices.append(i)
return ca_indices
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
Success
force_constant
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
# start
return (1.0/2.0)*(m1+m2)*(wave_len*(1.0/100.0))**2
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
# start
return (1.0/wave_len)*(m1*m2)/(m1+m2)
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
# Your code here
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
# start
mu = m1*m2/(m1+m2)
k = (wave_len*1e-2)**2*mu
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
# start
k = (m1*m2)/(m1+m2)*(wave_len*(1.0/100.0)*(1.0/2.0*np.pi*1.0e10))**2
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
Success
fourier_1d
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
# start
return np.fft.fft(x)
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
# begin
N = len(x)
X = np.zeros(N, dtype=np.complex)
for k in range(N):
for n in range(N):
X[k] += x[n]*np.exp(-2j*np.pi*k*n/N)
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
N = len(x)
X = np.zeros(N, dtype=complex)
for k in range(N):
for n in range(N):
X[k] += x[n] * np.exp(-2j * np.pi * k * n / N)
return X
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
# start
N = len(x)
X = np.zeros(N, dtype=np.complex)
for k in range(N):
for n in range(N):
X[k] += x[n] * np.exp(-2j * np.pi * k * n / N)
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
# start
N = x.shape[0]
X = np.zeros(N, dtype=np.complex)
for k in range(N):
for n in range(N):
X[k] += x[n] * np.exp(-2j * np.pi * k * n / N)
return X
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
Success
freezing_depression
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
return Kf * m
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
return Kf * m
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
return Kf * m
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
return Kf * m
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
return Kf * m
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
Success
genpos
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = 'http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-geninfo?gnum=' + str(gnum)
r = requests.get(url)
soup = BeautifulSoup(r.content, "html.parser")
table = soup.find_all('table')[0]
rows = table.find_all('tr')
generators = []
for row in rows:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
generators.append([ele for ele in cols if ele])
generators = generators[1:]
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
list index out of range
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = 'http://it.iucr.org/Ac/ch4o3pr3/sgtable/' + str(gnum) + '.html'
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')
table = soup.find('table', {'class': 'sgtable'})
rows = table.find_all('tr')
generators = []
for row in rows:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
generators.append([ele for ele in cols if ele])
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
'NoneType' object has no attribute 'find_all'
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
# get the page
url = "http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-geninfo?gnum=" + str(gnum)
r = requests.get(url)
# parse the page
soup = BeautifulSoup(r.content, "html.parser")
# get the table with generators
table = soup.find("table", {"class": "matrix"})
# get the rows
rows = table.find_all("tr")
# get the cells
cells = []
for row in rows:
cells.append(row.find_all("td"))
# get the values
values = []
for cell in cells:
values.append(cell[0].text)
# get the generators
generators = []
for i in range(0, len(values), 3):
generators.append(values[i:i+3])
# convert to numpy array
generators = np.array(generators, dtype=np.float64)
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
'NoneType' object has no attribute 'find_all'
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = 'http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-matrix_generators?gnum=' + str(gnum)
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
table = soup.find('table')
rows = table.find_all('tr')
matrices = []
for row in rows[1:]:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
matrices.append(cols)
return matrices
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
'NoneType' object has no attribute 'find_all'
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = "http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-geninfo?gnum=" + str(gnum) + "&tab=gen"
r = requests.get(url)
soup = BeautifulSoup(r.content, "html.parser")
table = soup.find_all("table")[1]
rows = table.find_all("tr")
matrices = []
for row in rows[1:]:
cols = row.find_all("td")
matrices.append(np.array([[float(cols[1].text), float(cols[2].text), float(cols[3].text)],
[float(cols[4].text), float(cols[5].text), float(cols[6].text)],
[float(cols[7].text), float(cols[8].text), float(cols[9].text)]]))
return matrices
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
list index out of range
heating_water
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
return n * (T2 - T1) * 4.184
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
return n * (T2 - T1) * 4.184
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
# start
c = 4.184
return c * n * (T2 - T1)
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
return n * 4.184 * (T2 - T1)
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
return n * 4.184 * (T2 - T1)
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
hydrophobic_res
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
# Load PDB file
pdb_file = md.load_pdb(pdb_filename)
# Get list of hydrophobic residues
hydrophobic_residues = [residue.index for residue in pdb_file.topology.residues if residue.is_hydrophobic]
# Return list of hydrophobic residues
return hydrophobic_residues
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
'Residue' object has no attribute 'is_hydrophobic'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
# Load PDB file
pdb = md.load_pdb(pdb_filename)
# Get list of hydrophobic residues
hydrophobic_residues = []
for residue in pdb.topology.residues:
if residue.is_water:
continue
if residue.is_protein:
if residue.name in ['ALA', 'VAL', 'LEU', 'ILE', 'PHE', 'TYR', 'TRP', 'MET', 'PRO']:
hydrophobic_residues.append(residue.index)
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
# load pdb file
traj = md.load(pdb_filename)
# get list of hydrophobic residues
hydrophobic_residues = []
for residue in traj.topology.residues:
if residue.is_water:
continue
if residue.name in ['ALA', 'VAL', 'LEU', 'ILE', 'MET', 'PHE', 'TRP', 'PRO']:
hydrophobic_residues.append(residue.index)
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
# load pdb file
pdb = md.load_pdb(pdb_filename)
# get residue names
residue_names = pdb.topology.residue_names()
# get residue indices
residue_indices = pdb.topology.residue_indices()
# get hydrophobic residues
hydrophobic_residues = []
for i in range(len(residue_names)):
if residue_names[i] in ['ALA', 'ILE', 'LEU', 'VAL', 'PHE', 'TYR', 'TRP', 'MET']:
hydrophobic_residues.append(residue_indices[i])
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
'Topology' object has no attribute 'residue_names'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
# Load PDB file
pdb_file = md.load_pdb(pdb_filename)
# Get list of hydrophobic residues
hydrophobic_residues = [residue.index for residue in pdb_file.topology.residues if residue.is_hydrophobic]
# Return list of hydrophobic residues
return hydrophobic_residues
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
'Residue' object has no attribute 'is_hydrophobic'
ideal_gas
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.08205746 # atm L / mol K
return n * R * T / V
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.08205746 # L atm / mol K
return n * R * T / V
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.08205746 # atm L / mol K
return n * R * T / V
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.08205746 # atm L / mol K
return n * R * T / V
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.08206 # atm L / mol K
return n * R * T / V
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
integral
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
return a*d**3/4 + b*d**2/3 + c*d
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
# start
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
Success
trap
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
h = (b-a)/n
x = np.linspace(a, b, n+1)
y = f(x)
return h*(0.5*y[0] + 0.5*y[-1] + np.sum(y[1:-1]))
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
h = (b-a)/n
x = np.linspace(a, b, n+1)
y = f(x)
return h*(0.5*y[0] + 0.5*y[-1] + np.sum(y[1:-1]))
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
h = (b - a) / n
x = np.linspace(a, b, n + 1)
y = f(x)
return h / 2 * (y[0] + 2 * np.sum(y[1:-1]) + y[-1])
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
h = (b - a) / n
s = 0.5 * (f(a) + f(b))
for i in range(1, n):
s = s + f(a + i * h)
return s * h
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
h = (b-a)/n
x = np.linspace(a,b,n+1)
y = f(x)
return h*(0.5*y[0] + 0.5*y[-1] + np.sum(y[1:-1]))
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
invert_matrix
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
# your code here
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
return np.linalg.inv(A)
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
# TODO: Compute the inverse of matrix A
inv_A = np.linalg.inv(A)
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
# start
A_inv = np.linalg.inv(A)
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
# Compute the inverse of A
A_inv = np.linalg.inv(A)
return A_inv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
iupac2smiles
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(IUPAC)))
return Chem.MolToSmiles(mol)
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
Python argument types in
rdkit.Chem.rdmolfiles.MolToSmiles(NoneType)
did not match C++ signature:
MolToSmiles(RDKit::ROMol mol, bool isomericSmiles=True, bool kekuleSmiles=False, int rootedAtAtom=-1, bool canonical=True, bool allBondsExplicit=False, bool allHsExplicit=False, bool doRandom=False)
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(IUPAC)))
return Chem.MolToSmiles(mol)
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
Python argument types in
rdkit.Chem.rdmolfiles.MolToSmiles(NoneType)
did not match C++ signature:
MolToSmiles(RDKit::ROMol mol, bool isomericSmiles=True, bool kekuleSmiles=False, int rootedAtAtom=-1, bool canonical=True, bool allBondsExplicit=False, bool allHsExplicit=False, bool doRandom=False)
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
return Chem.MolToSmiles(Chem.MolFromSmiles(IUPAC))
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
Python argument types in
rdkit.Chem.rdmolfiles.MolToSmiles(NoneType)
did not match C++ signature:
MolToSmiles(RDKit::ROMol mol, bool isomericSmiles=True, bool kekuleSmiles=False, int rootedAtAtom=-1, bool canonical=True, bool allBondsExplicit=False, bool allHsExplicit=False, bool doRandom=False)
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(IUPAC)))
return Chem.MolToSmiles(mol)
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
Python argument types in
rdkit.Chem.rdmolfiles.MolToSmiles(NoneType)
did not match C++ signature:
MolToSmiles(RDKit::ROMol mol, bool isomericSmiles=True, bool kekuleSmiles=False, int rootedAtAtom=-1, bool canonical=True, bool allBondsExplicit=False, bool allHsExplicit=False, bool doRandom=False)
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolTo
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
kld
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
# start
kl_loss = np.sum(np.where(true_data != 0, true_data * np.log(true_data / predicted_data), 0))
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
# start
# Calculate the KL divergence loss between true_data and predicted_data
kl_loss = np.sum(true_data * np.log(true_data / predicted_data))
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
# YOUR CODE HERE
#raise NotImplementedError()
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
# start
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
# start
kl_loss = np.sum(np.where(true_data != 0, true_data * np.log(true_data / predicted_data), 0))
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
langevin_dynamics
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(n_steps-1):
x_traj[i+1] = x_traj[i] + dt*v_traj[i]
v_traj[i+1] = v_traj[i] + dt*(F(x_traj[i])/m - gamma*v_traj[i] + np.sqrt(2*gamma*T/m)*np.random.normal())
return x_traj,v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(n_steps-1):
v_traj[i+1] = v_traj[i] - (gamma/m)*v_traj[i]*dt + (1/m)*F(x_traj[i])*dt + np.sqrt(2*gamma*T*dt/m)*np.random.normal()
x_traj[i+1] = x_traj[i] + v_traj[i+1]*dt
return x_traj,v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(n_steps-1):
x_traj[i+1] = x_traj[i] + v_traj[i]*dt + 0.5*F(x_traj[i])*dt**2/m
v_traj[i+1] = v_traj[i] + 0.5*(F(x_traj[i])/m + F(x_traj[i+1])/m)*dt + np.sqrt(2*gamma*T/m)*np.random.normal()*np.sqrt(dt)
return x_traj,v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(n_steps-1):
v_traj[i+1] = v_traj[i] - gamma/m*v_traj[i]*dt + F(x_traj[i])/m*dt + np.sqrt(2*gamma*T/m)*np.sqrt(dt)*np.random.normal()
x_traj[i+1] = x_traj[i] + v_traj[i+1]*dt
return x_traj,v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(n_steps-1):
v_traj[i+1] = v_traj[i] - (gamma/m)*v_traj[i]*dt + (1/m)*F(x_traj[i])*dt + np.sqrt(2*gamma*T*dt/m)*np.random.normal()
x_traj[i+1] = x_traj[i] + v_traj[i+1]*dt
return x_traj,v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
Success
weighted-least-squares
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
# start
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
return np.linalg.inv(x.T.dot(np.diag(w).dot(x))).dot(x.T).dot(np.diag(w).dot(y))
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
return np.linalg.lstsq(x.T.dot(w).dot(x), x.T.dot(w).dot(y))[0]
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
shapes (3,) and (100,3) not aligned: 3 (dim 0) != 100 (dim 0)
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
# TODO: implement weighted least squares
# start
x = np.matrix(x)
w = np.matrix(w)
y = np.matrix(y)
w_inv = np.linalg.inv(np.diag(w))
x_t = np.transpose(x)
x_t_w_inv = np.dot(x_t, w_inv)
x_t_w_inv_x = np.dot(x_t_w_inv, x)
x_t_w_inv_x_inv = np.linalg.inv(x_t_w_inv_x)
x_t_w_inv_y = np.dot(x_t_w_inv, y)
coeff = np.dot(x_t_w_inv_x_inv, x_t_w_inv_y)
return coeff
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
1-dimensional array given. Array must be at least two-dimensional
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
# TODO: Implement weighted least squares
# start
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
lipinski_rule_of_five
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
# get the molecule from the SMILES string
mol = Chem.MolFromSmiles(smiles)
# calculate the number of hydrogen bond donors
hbd = rdMolDescriptors.CalcNumHBD(mol)
# calculate the number of hydrogen bond acceptors
hba = rdMolDescriptors.CalcNumHBA(mol)
# calculate the molecular weight
mw = Descriptors.MolWt(mol)
# calculate the logP
logp = Crippen.MolLogP(mol)
# check if the molecule satisfies Lipinski's rule of five
if hbd <= 5 and hba <= 10 and mw < 500 and logp < 5:
return True
else:
return False
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
m = Chem.MolFromSmiles(smiles)
if m is None:
return False
else:
return (rdMolDescriptors.CalcNumHBD(m) <= 5 and rdMolDescriptors.CalcNumHBA(m) <= 10 and Descriptors.MolWt(m) < 500 and Crippen.MolLogP(m) < 5)
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return False
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return False
else:
hbd = Descriptors.NumHDonors(mol)
hba = Descriptors.NumHAcceptors(mol)
mw = Descriptors.MolWt(mol)
logp = Crippen.MolLogP(mol)
if hbd <= 5 and hba <= 10 and mw < 500 and logp < 5:
return True
else:
return False
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
m = Chem.MolFromSmiles(smiles)
if m is None:
return False
if rdMolDescriptors.CalcNumHBD(m) > 5:
return False
if rdMolDescriptors.CalcNumHBA(m) > 10:
return False
if Descriptors.MolWt(m) > 500:
return False
if Crippen.MolLogP(m) > 5:
return False
return True
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
Success
mape
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
return np.mean(np.abs((y-y_hat)/y))
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
# start
mape = 0
for i in range(len(y)):
mape += abs(y_hat[i] - y[i]) / y[i]
mape /= len(y)
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
return np.mean(np.abs((y-y_hat)/y))
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
return np.mean(np.abs((y-y_hat)/y))
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
return np.mean(np.abs((y-y_hat)/y))
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
Success
mapping_operator
import MDAnalysis
import numpy as np
"""
Print version string
"""
print(MDAnalysis.__version__)
# end
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
import MDAnalysis
import numpy as np
"""
Print version string
"""
print(MDAnalysis.__version__)
# end
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
# get the number of beads
nbeads = len(beads_mappings)
# get the number of atoms
natoms = molecule.atoms.n_atoms
# create the mapping matrix
mapping_matrix = np.zeros((nbeads, natoms))
# loop over the beads
for i in range(nbeads):
# get the selection
selection = beads_mappings[i]
# get the indices
indices = selection.indices
# get the masses
masses = selection.masses
# get the number of atoms in the bead
nbead_atoms = len(indices)
# loop over the atoms
for j in range(nbead_atoms):
# get the index
index = indices[j]
# get the mass
mass = masses[j]
# set the mapping matrix
mapping_matrix[i, index] = mass
# return the mapping matrix
return mapping_matrix
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
'list' object has no attribute 'indices'
import MDAnalysis
import numpy as np
"""
Print version string
"""
print(MDAnalysis.__version__)
# end
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
# get the number of beads
n_beads = len(beads_mappings)
# get the number of atoms
n_atoms = molecule.n_atoms
# create the mapping matrix
mapping_matrix = np.zeros((n_beads, n_atoms))
# loop over the beads
for bead_index in range(n_beads):
# get the bead selection
bead_selection = beads_mappings[bead_index]
# get the bead masses
bead_masses = molecule.atoms.masses[bead_selection]
# get the bead masses sum
bead_masses_sum = bead_masses.sum()
# get the bead masses normalized
bead_masses_normalized = bead_masses / bead_masses_sum
# set the bead masses normalized in the mapping matrix
mapping_matrix[bead_index, bead_selection] = bead_masses_normalized
# return the mapping matrix
return mapping_matrix
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
import MDAnalysis
import numpy as np
"""
Print version string
"""
print(MDAnalysis.__version__)
# end
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
# get the number of beads
n_beads = len(beads_mappings)
# get the number of atoms
n_atoms = molecule.n_atoms
# create the mapping matrix
mapping = np.zeros((n_beads, n_atoms))
# loop over the beads
for i, bead in enumerate(beads_mappings):
# get the selection
selection = molecule.select_atoms(bead)
# get the masses
masses = selection.masses
# get the number of atoms in the selection
n_selection = selection.n_atoms
# get the indices of the atoms in the selection
indices = selection.indices
# create a temporary mapping matrix
temp_mapping = np.zeros((n_beads, n_atoms))
# set the diagonal elements
temp_mapping[i, indices] = masses
# add the temporary mapping matrix to the mapping matrix
mapping += temp_mapping
# return the mapping matrix
return mapping
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
'list' object has no attribute 'replace'
import MDAnalysis
import numpy as np
"""
Print version string
"""
print(MDAnalysis.__version__)
# end
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
# get the number of beads
n_beads = len(beads_mappings)
# get the number of atoms
n_atoms = molecule.n_atoms
# create the mapping matrix
mapping_matrix = np.zeros((n_beads, n_atoms))
# loop over the beads
for bead_index, bead_selection in enumerate(beads_mappings):
# get the indices of the atoms in the bead
bead_indices = bead_selection.indices
# get the masses of the atoms in the bead
bead_masses = molecule.masses[bead_indices]
# get the total mass of the bead
bead_mass = np.sum(bead_masses)
# set the mapping matrix
mapping_matrix[bead_index, bead_indices] = bead_masses / bead_mass
# return the mapping matrix
return mapping_matrix
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
'list' object has no attribute 'indices'
import MDAnalysis
import numpy as np
"""
Print version string
"""
print(MDAnalysis.__version__)
# end
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
# get the number of beads
n_beads = len(beads_mappings)
# get the number of atoms
n_atoms = molecule.n_atoms
# create the mapping matrix
mapping_matrix = np.zeros((n_beads, n_atoms))
# loop over the beads
for bead_index in range(n_beads):
# get the bead
bead = beads_mappings[bead_index]
# get the atoms
atoms = bead.atoms
# get the masses
masses = atoms.masses
# get the total mass
total_mass = masses.sum()
# get the number of atoms
n_atoms = len(atoms)
# loop over the atoms
for atom_index in range(n_atoms):
# get the atom
atom = atoms[atom_index]
# get the mass
mass = atom.mass
# get the atom index
atom_index = atom.index
# set the mapping matrix
mapping_matrix[bead_index, atom_index] = mass / total_mass
# return the mapping matrix
return mapping_matrix
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
'list' object has no attribute 'atoms'
matpow
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
if n == 0:
return np.eye(x.shape[0])
elif n == 1:
return x
elif n % 2 == 0:
return matpow(x.dot(x), n/2)
else:
return x.dot(matpow(x, n-1))
"""
Compute matrix x raised to the power n
"""
b = matpow(a,10)
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
shapes (5,10) and (5,10) not aligned: 10 (dim 1) != 5 (dim 0)
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
if n == 0:
return np.identity(x.shape[0])
elif n == 1:
return x
else:
return np.dot(x,matpow(x,n-1))
"""
Compute matrix power
"""
b = matpow(a,3)
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
shapes (5,10) and (5,10) not aligned: 10 (dim 1) != 5 (dim 0)
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
if n == 0:
return np.eye(x.shape[0])
elif n == 1:
return x
elif n % 2 == 0:
return matpow(np.dot(x,x), n/2)
else:
return np.dot(x, matpow(np.dot(x,x), (n-1)/2))
"""
Compute matrix power
"""
a = matpow(a, 2)
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
shapes (5,10) and (5,10) not aligned: 10 (dim 1) != 5 (dim 0)
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
if n == 0:
return np.identity(x.shape[0])
elif n == 1:
return x
elif n % 2 == 0:
return matpow(np.dot(x,x), n/2)
else:
return np.dot(x, matpow(np.dot(x,x), (n-1)/2))
"""
Compute matrix x raised to the power n
"""
b = matpow(a,3)
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
shapes (5,10) and (5,10) not aligned: 10 (dim 1) != 5 (dim 0)
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
if n == 0:
return np.identity(x.shape[0])
elif n == 1:
return x
else:
return np.dot(x, matpow(x,n-1))
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
matrix_factorial
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
return np.array([np.math.factorial(i) for i in n])
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
only integer scalar arrays can be converted to a scalar index
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
# start
return np.array([np.math.factorial(i) for i in n])
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
only integer scalar arrays can be converted to a scalar index
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
# start
return np.array([np.math.factorial(i) for i in n])
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
only integer scalar arrays can be converted to a scalar index
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
# start
return np.array([np.math.factorial(i) for i in n])
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
only integer scalar arrays can be converted to a scalar index
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
# start
return np.array(list(map(lambda x: math.factorial(x), n)))
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
name 'math' is not defined
max-boltz
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.3806488e-23
return math.sqrt(3*k*T/M)
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.3806488e-23
return math.sqrt(3 * k * T / M)
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.3806488e-23
return math.sqrt(k*T/M)
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.3806488e-23 # Boltzmann constant in J/K
return math.sqrt(k*T/M)
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.3806503e-23 # Boltzmann constant
return math.sqrt(k*T/M)
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
Success
michaelis
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
return Vmax * S / (Km + S)
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
return Vmax * S / (Km + S)
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
return Vmax * S / (Km + S)
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
return Vmax * S / (Km + S)
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
return Vmax * S / (Km + S)
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
mol_charge
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
return Chem.GetFormalCharge(mol)
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
return Descriptors.MolWt(mol)
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
return Chem.GetFormalCharge(mol)
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
return mol.GetFormalCharge()
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
'Mol' object has no attribute 'GetFormalCharge'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
return Chem.GetFormalCharge(mol)
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
net_charge
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
# start
charge = 0
for aa in sequence:
if aa == 'K' or aa == 'R':
charge += 1
elif aa == 'D' or aa == 'E':
charge -= 1
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for aa in sequence:
if aa == 'K' or aa == 'R':
charge += 1
elif aa == 'D' or aa == 'E':
charge -= 1
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for aa in sequence:
if aa == 'K' or aa == 'R':
charge += 1
elif aa == 'D' or aa == 'E':
charge -= 1
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
net_charge = 0
for aa in sequence:
if aa == "K" or aa == "R":
net_charge += 1
elif aa == "D" or aa == "E":
net_charge -= 1
return net_charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
# start
net_charge = 0
for aa in sequence:
if aa == 'K' or aa == 'R':
net_charge += 1
elif aa == 'D' or aa == 'E':
net_charge -= 1
return net_charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
Success
solve_ode
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
# Initialize
y = np.zeros((len(t), len(y0)))
y[0] = y0
h = t[1] - t[0]
# Loop
for i in range(len(t)-1):
k1 = fn(t[i], y[i])
k2 = fn(t[i] + h/4, y[i] + h/4*k1)
k3 = fn(t[i] + 3*h/8, y[i] + 3*h/32*k1 + 9*h/32*k2)
k4 = fn(t[i] + 12*h/13, y[i] + 1932*h/2197*k1 - 7200*h/2197*k2 + 7296*h/2197*k3)
k5 = fn(t[i] + h, y[i] + 439*h/216*k1 - 8*h*k2 + 3680*h/513*k3 - 845*h/4104*k4)
k6 = fn(t[i] + h/2, y[i] - 8*h/27*k1 + 2*h*k2 - 3544*h/2565*k3 + 1859*h/4104*k4 - 11*h/40*k5)
y[i+1] = y[i] + h/6*(25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5)
return y
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
# Initialize
y = np.zeros((len(t), len(y0)))
y[0,:] = y0
h = t[1] - t[0]
# Loop
for i in range(len(t)-1):
k1 = h*fn(t[i], y[i,:])
k2 = h*fn(t[i] + h/4, y[i,:] + k1/4)
k3 = h*fn(t[i] + 3*h/8, y[i,:] + 3*k1/32 + 9*k2/32)
k4 = h*fn(t[i] + 12*h/13, y[i,:] + 1932*k1/2197 - 7200*k2/2197 + 7296*k3/2197)
k5 = h*fn(t[i] + h, y[i,:] + 439*k1/216 - 8*k2 + 3680*k3/513 - 845*k4/4104)
k6 = h*fn(t[i] + h/2, y[i,:] - 8*k1/27 + 2*k2 - 3544*k3/2565 + 1859*k4/4104 - 11*k5/40)
y[i+1,:] = y[i,:] + 25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5
return y
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
y = np.zeros((len(t), len(y0)))
y[0] = y0
for i in range(len(t)-1):
h = t[i+1] - t[i]
k1 = h * fn(t[i], y[i])
k2 = h * fn(t[i] + h/4, y[i] + k1/4)
k3 = h * fn(t[i] + 3*h/8, y[i] + 3*k1/32 + 9*k2/32)
k4 = h * fn(t[i] + 12*h/13, y[i] + 1932*k1/2197 - 7200*k2/2197 + 7296*k3/2197)
k5 = h * fn(t[i] + h, y[i] + 439*k1/216 - 8*k2 + 3680*k3/513 - 845*k4/4104)
k6 = h * fn(t[i] + h/2, y[i] - 8*k1/27 + 2*k2 - 3544*k3/2565 + 1859*k4/4104 - 11*k5/40)
y[i+1] = y[i] + 25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5
return y
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
y = np.zeros((len(t), len(y0)))
y[0] = y0
for i in range(len(t)-1):
h = t[i+1] - t[i]
k1 = fn(t[i], y[i])
k2 = fn(t[i] + h/4, y[i] + h*k1/4)
k3 = fn(t[i] + 3*h/8, y[i] + 3*h*k1/32 + 9*h*k2/32)
k4 = fn(t[i] + 12*h/13, y[i] + 1932*h*k1/2197 - 7200*h*k2/2197 + 7296*h*k3/2197)
k5 = fn(t[i] + h, y[i] + 439*h*k1/216 - 8*h*k2 + 3680*h*k3/513 - 845*h*k4/4104)
k6 = fn(t[i] + h/2, y[i] - 8*h*k1/27 + 2*h*k2 - 3544*h*k3/2565 + 1859*h*k4/4104 - 11*h*k5/40)
y[i+1] = y[i] + h*(25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5)
return y
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
# Initialize
y = np.zeros((len(t), len(y0)))
y[0,:] = y0
h = t[1] - t[0]
# Iterate
for i in range(len(t)-1):
k1 = h*fn(t[i], y[i,:])
k2 = h*fn(t[i] + h/4, y[i,:] + k1/4)
k3 = h*fn(t[i] + 3*h/8, y[i,:] + 3*k1/32 + 9*k2/32)
k4 = h*fn(t[i] + 12*h/13, y[i,:] + 1932*k1/2197 - 7200*k2/2197 + 7296*k3/2197)
k5 = h*fn(t[i] + h, y[i,:] + 439*k1/216 - 8*k2 + 3680*k3/513 - 845*k4/4104)
k6 = h*fn(t[i] + h/2, y[i,:] - 8*k1/27 + 2*k2 - 3544*k3/2565 + 1859*k4/4104 - 11*k5/40)
y[i+1,:] = y[i,:] + 25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5
return y
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
ohe
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
# YOUR CODE HERE
raise NotImplementedError()
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
# YOUR CODE HERE
# raise NotImplementedError()
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
# YOUR CODE HERE
#raise NotImplementedError()
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
# YOUR CODE HERE
#raise NotImplementedError()
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
# start
return np.eye(len(a))
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
operands could not be broadcast together with shapes (10,10) (10,5)
osmotic_pressure
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
return Pi / (R * T)
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
return Pi / (R * T)
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
return Pi/(R*T)
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
return Pi/(R*T)
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
return Pi / (R * T)
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
Success
pair_wise
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
# Load the pdb file
traj = md.load(pdb_file)
# Select only the alpha carbons
alpha_carbons = traj.topology.select('name CA')
# Calculate the number of unique alpha carbon pairs
num_pairs = len(alpha_carbons) * (len(alpha_carbons) - 1) / 2
# Calculate the distances between each alpha carbon pair
distances = md.compute_distances(traj, alpha_carbons, alpha_carbons)
# Return the distances between each alpha carbon pair
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
# Load the pdb file
traj = md.load(pdb_file)
# Select only the alpha carbons
alpha_carbons = traj.topology.select("name CA")
# Calculate the number of unique alpha carbon pairs
num_pairs = len(alpha_carbons) * (len(alpha_carbons) - 1) / 2
# Calculate the distances between each alpha carbon pair
distances = md.compute_distances(traj, alpha_carbons, alpha_carbons)
# Return the distances
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
# 1
traj = md.load(pdb_file)
# 2
alpha_carbons = traj.topology.select('name CA')
# 3
pairs = list(itertools.combinations(alpha_carbons, 2))
# 4
distances = md.compute_distances(traj, pairs)
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
# Load the pdb file
traj = md.load(pdb_file)
# Select only the alpha carbons
traj.atom_slice(traj.topology.select('name CA'), inplace=True)
# Calculate the number of unique alpha carbon pairs
n_pairs = traj.n_atoms * (traj.n_atoms - 1) / 2
# Calculate the distances between each alpha carbon pair
pairwise_distances = md.compute_distances(traj, [(i, j) for i in range(traj.n_atoms) for j in range(i)])
# Return the distances between each alpha carbon pair
return pairwise_distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
# Load the pdb file
traj = md.load(pdb_file)
# Select only the alpha carbons
traj = traj.atom_slice(traj.topology.select('name CA'))
# Calculate the number of unique alpha carbon pairs
n_pairs = traj.n_atoms * (traj.n_atoms - 1) / 2
# Calculate the distances between each alpha carbon pair
dist = md.compute_distances(traj, [(i, j) for i in range(traj.n_atoms) for j in range(i)])
# Return the distances between each alpha carbon pair
return dist
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
pi
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
x = np.random.uniform(0,1,nsamples)
y = np.random.uniform(0,1,nsamples)
r = np.sqrt(x**2 + y**2)
return 4*np.sum(r<1)/nsamples
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
# create a matrix of random numbers
x = np.random.rand(nsamples,2)
# compute the distance from the origin
r = np.sqrt(x[:,0]**2 + x[:,1]**2)
# count the number of points inside the unit circle
inside = np.sum(r<1)
# compute the value of pi
return 4*inside/nsamples
print(pi(1000000))
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
x = np.random.rand(nsamples)
y = np.random.rand(nsamples)
r = np.sqrt(x**2 + y**2)
return 4.0 * np.sum(r < 1.0) / nsamples
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
x = np.random.uniform(0,1,nsamples)
y = np.random.uniform(0,1,nsamples)
r = np.sqrt(x**2 + y**2)
return 4*np.sum(r<1)/nsamples
print(pi(1000000))
"""
Create matrix of ones
"""
a = np.ones((5,10))
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
# create a matrix of random numbers
x = np.random.rand(nsamples,2)
# calculate the distance from the origin
r = np.sqrt(x[:,0]**2 + x[:,1]**2)
# count the number of points within a unit circle
n = np.sum(r < 1)
# return the value of pi
return 4*n/nsamples
print(pi(1000000))
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
pib_1d
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
return (n*n*math.pi*math.pi*hbar*hbar)/(2*m*L*L)
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
return (n**2 * math.pi**2 * hbar**2)/(2 * m * L**2)
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
return (n**2 * math.pi**2 * hbar**2) / (2 * m * L**2)
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
return (n**2 * math.pi**2 * hbar**2) / (2 * m * L**2)
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
return n**2 * math.pi**2 * hbar**2 / (2 * m * L**2)
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
pred_interval
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
return np.ceil(np.log(1-pred_level)/np.log(1-p))
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
return np.ceil(np.log(1-pred_level)/np.log(1-p))
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
return int(np.ceil(np.log(1-pred_level)/np.log(1-p)))
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
return int(np.ceil(np.log(1-pred_level)/np.log(1-p)))
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
return np.ceil(np.log(1-pred_level)/np.log(1-p))
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
Success
pubchem
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/%s/cids/TXT?cids_type=similarity&Threshold=80' % smiles
response = requests.get(url)
if response.status_code == 200:
return set(response.text.split())
else:
return set()
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/%s/cids/TXT" % smiles
response = requests.get(url)
cids = response.text.split()
cid_string = ",".join(cids)
url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/%s/property/CanonicalSMILES/TXT" % cid_string
response = requests.get(url)
return set(response.text.split())
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/%s/cids/TXT" % smiles
response = requests.get(url)
cids = response.text.split()
cids = ",".join(cids)
url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/%s/property/CanonicalSMILES/TXT" % cids
response = requests.get(url)
return set(response.text.split())
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/%s/cids/TXT" % smiles
response = requests.get(url)
if response.status_code == 200:
cids = response.text.split()
url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/%s/property/CanonicalSMILES/TXT" % ",".join(cids)
response = requests.get(url)
if response.status_code == 200:
return set(response.text.split())
return set()
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
# PubChem REST API
url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/%s/cids/TXT" % smiles
# get the response
response = requests.get(url)
# convert the response to a string
response_string = response.content.decode("utf-8")
# split the string into a list of CIDs
cids = response_string.split()
# convert the list of CIDs to a set
cids = set(cids)
# remove the CID for the query molecule
cids.remove(str(Chem.MolToCID(Chem.MolFromSmiles(smiles))))
# convert the CIDs to SMILES strings
smiles_list = [Chem.MolToSmiles(x) for x in Chem.SDMolSupplier("https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/%s/sdf" % ",".join(cids))]
# return the list of SMILES strings
return smiles_list
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
module 'rdkit.Chem' has no attribute 'MolToCID'
pyscf_energy
import pyscf
import numpy as np
"""
Print pyscf version string
"""
print(pyscf.__version__)
# end
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
import pyscf
import numpy as np
"""
Print pyscf version string
"""
print(pyscf.__version__)
# end
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom, basis=basis)
mf = pyscf.scf.RHF(mol)
mf.kernel()
return mf.e_tot
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
"""
Print pyscf version string
"""
print(pyscf.__version__)
# end
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.Mole()
mol.atom = atom
mol.basis = basis
mol.build()
mf = pyscf.scf.RHF(mol)
mf.scf()
return mf.e_tot
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
"""
Print pyscf version string
"""
print(pyscf.__version__)
# end
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
# Create molecule object
mol = pyscf.gto.Mole()
# Add atom
mol.atom = atom
# Set basis
mol.basis = basis
# Set charge and multiplicity
mol.charge = 0
mol.spin = 0
# Build molecule
mol.build()
# Create Hartree-Fock object
mf = pyscf.scf.RHF(mol)
# Compute ground state energy
mf.kernel()
# Return energy
return mf.e_tot
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
"""
Print pyscf version string
"""
print(pyscf.__version__)
# end
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom, basis=basis)
mf = pyscf.scf.RHF(mol)
mf.scf()
return mf.e_tot
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
"""
Print pyscf version string
"""
print(pyscf.__version__)
# end
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom,basis=basis)
mf = pyscf.scf.RHF(mol)
mf.scf()
return mf.e_tot
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
qed
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
return Descriptors.qed(mol)
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
return Descriptors.qed(mol)
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
return Descriptors.qed(mol)
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
return Descriptors.qed(mol)
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
return Descriptors.qed(mol)
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
Success
quantile
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
# start
return np.percentile(a, q*100)
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
operands could not be broadcast together with shapes (300,) (3,)
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
# start
return np.quantile(a, q)
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
return np.percentile(a, q*100)
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
operands could not be broadcast together with shapes (300,) (3,)
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
# start
return np.percentile(a, q * 100)
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
operands could not be broadcast together with shapes (300,) (3,)
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
return np.percentile(a, q*100)
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
operands could not be broadcast together with shapes (300,) (3,)
random_walk
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
x = np.zeros(N)
x[0] = x0
for i in range(1,N):
x[i] = x[i-1] + a*(2*np.random.randint(2)-1)
return x
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
x = np.zeros(N)
x[0] = x0
for i in range(1,N):
x[i] = x[i-1] + a*(np.random.randint(2)*2-1)
return x
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
x = np.zeros(N)
x[0] = x0
for i in range(1,N):
x[i] = x[i-1] + a*(2*np.random.randint(2)-1)
return x
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
x = np.zeros(N)
x[0] = x0
for i in range(1,N):
x[i] = x[i-1] + a*(2*np.random.randint(2)-1)
return x
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
x = np.zeros(N)
x[0] = x0
for i in range(1,N):
x[i] = x[i-1] + a*(np.random.randint(2)*2-1)
return x
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
Success
rank
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M)
return np.sum(s > 1e-10)
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M)
return np.sum(s > 1e-10)
"""
Create matrix of zeros
"""
b = np.zeros((5,10))
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, S, V = np.linalg.svd(M)
return np.sum(S > 1e-10)
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M)
return np.sum(s > 1e-10)
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, S, V = np.linalg.svd(M)
return np.sum(S > 1e-12)
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
remove-water
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
traj.remove_solvent()
return traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
traj.remove_solvent()
return traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
traj.remove_solvent(inplace=True)
return traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
traj.remove_solvent(inplace=True)
return traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
traj.remove_solvent(inplace=True)
return traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
Success
rms_velocity
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38e-23 # Boltzmann constant in J/K
return math.sqrt(3*k*T/m)
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38e-23 # Boltzmann constant
return math.sqrt(3*k*T/m)
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.3806488e-23
return math.sqrt(3*k*T/m)
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38e-23 # Boltzmann constant
return math.sqrt(3*k*T/m)
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38e-23 # Boltzmann constant in J/K
return math.sqrt(3 * k * T / m)
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
rmse
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
return np.sqrt(np.mean((a-b)**2))
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
return np.sqrt(np.mean((a-b)**2))
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
return np.sqrt(np.mean((a-b)**2))
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
return np.sqrt(np.mean((a-b)**2))
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
return np.sqrt(np.mean((a-b)**2))
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
Success
rog
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
# Load the pdb file
traj = md.load(pdb_file)
# Calculate the radius of gyration
radius_of_gyration = md.compute_rg(traj)
# Return the radius of gyration
return radius_of_gyration
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
# Load the pdb file
traj = md.load(pdb_file)
# Calculate the radius of gyration
rgyr = md.compute_rg(traj)
# Return the radius of gyration
return rgyr
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
# Load the pdb file
traj = md.load(pdb_file)
# Calculate the radius of gyration
radius_of_gyration = md.compute_rg(traj)
# Return the radius of gyration
return radius_of_gyration
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
# Load the pdb file
traj = md.load(pdb_file)
# Calculate the radius of gyration
radius_of_gyration = md.compute_rg(traj)
# Return the radius of gyration
return radius_of_gyration
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
traj = md.load(pdb_file)
return md.compute_rg(traj)
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
sasa
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
traj = md.load(pdb_file)
topology = traj.topology
atoms, bonds = topology.to_dataframe()
sasa = md.shrake_rupley(traj, mode='residue')
sasa_df = pd.DataFrame(sasa, columns=['sasa'])
sasa_df['resSeq'] = atoms['resSeq']
sasa_df['resName'] = atoms['resName']
sasa_df['chainID'] = atoms['chainID']
sasa_df = sasa_df.groupby(['resSeq', 'resName', 'chainID']).sum()
return sasa_df
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
name 'pd' is not defined
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
# Load pdb
traj = md.load(pdb_file)
# Calculate sasa
sasa = md.shrake_rupley(traj)
# Return sasa
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
# Load the pdb
traj = md.load(pdb_file)
# Calculate the sasa
sasa = md.shrake_rupley(traj)
# Return the sasa
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
traj = md.load_pdb(pdb_file)
sasa = md.shrake_rupley(traj)
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
# Load the pdb
traj = md.load(pdb_file)
# Calculate the sasa
sasa = md.shrake_rupley(traj)
# Return the sasa
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
Success
scaffold
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
core = Chem.MolFromSmiles(Chem.MolToSmiles(mol, True))
for a in core.GetAtoms():
a.SetAtomMapNum(0)
scaffold = Chem.MolToSmiles(core, True, False, True)
return scaffold
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
engine = rdMolDescriptors.GetMorganFingerprint(mol, 2)
arr = np.zeros((1,))
DataStructs.ConvertToNumpyArray(engine, arr)
df = pd.DataFrame(arr.reshape(1, arr.shape[0]))
return df
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
engine = Scaffold.ScaffoldGenerator()
scaffold = engine.GetScaffoldForMol(mol)
return Chem.MolToSmiles(scaffold, isomericSmiles=True)
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
name 'Scaffold' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
scaffold = Chem.MolFromSmiles(Chem.MolToSmiles(mol,True))
core = Chem.DeleteSubstructs(scaffold,Chem.MolFromSmiles('[*]'))
return Chem.MolToSmiles(core)
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
scaffold = Chem.MolFromSmarts(Chem.MolToSmarts(mol))
return Chem.MolToSmiles(scaffold)
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
Success
seq-align
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
top_aln = alns[0]
aln_seq1, aln_seq2, score, begin, end = top_aln
return aln_seq1, aln_seq2
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
top_aln = alns[0]
aln1, aln2, score, begin, end = top_aln
return aln1, aln2
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
seq1 = alns[0][0]
seq2 = alns[0][1]
return(seq1, seq2)
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
return alns
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
top_aln = alns[0]
aln_seq1, aln_seq2, score, begin, end = top_aln
return aln_seq1, aln_seq2
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
Success
seq-trans
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
return Seq(gene_seq).translate()
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
return Seq(gene_seq).translate()
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
return Seq(gene_seq).translate()
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
gene_seq = Seq(gene_seq)
return gene_seq.translate()
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
return Seq(gene_seq).translate()
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
sequence
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
return np.linspace(s,e,l)
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
return np.linspace(s,e,l)
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
return np.linspace(s,e,l)
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
return np.geomspace(s,e,l)
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
return np.linspace(s,e,l)
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
Success
sle
import sympy
"""
print sympy version
"""
print(sympy.__version__)
# end
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
import sympy
"""
print sympy version
"""
print(sympy.__version__)
# end
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
# create a list of variables
vars = []
for eqn in eqns:
for var in eqn.split('+'):
if var.split('-')[0].split('=')[0].strip() not in vars:
vars.append(var.split('-')[0].split('=')[0].strip())
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
'NoneType' object has no attribute 'values'
import sympy
"""
print sympy version
"""
print(sympy.__version__)
# end
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
# create a list of symbols
symbols = []
for i in range(len(eqns)):
symbols.append(sympy.Symbol('x_' + str(i)))
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
'NoneType' object has no attribute 'values'
import sympy
"""
print sympy version
"""
print(sympy.__version__)
# end
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
# create a list of variables
x = sympy.symbols('x:%d' % len(eqns))
# create a list of equations
eqns = [sympy.sympify(eq) for eq in eqns]
# solve the system of linear equations
sol = sympy.solve(eqns, x)
# return the solution
return sol
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
import sympy
"""
print sympy version
"""
print(sympy.__version__)
# end
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
eqns = [sympy.Eq(eqn) for eqn in eqns]
return sympy.solve(eqns, dict=True)
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
SympifyError: '4x + 3y = 20'
import sympy
"""
print sympy version
"""
print(sympy.__version__)
# end
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
eqns = [sympy.Eq(eqn) for eqn in eqns]
return sympy.solve(eqns)
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
SympifyError: '4x + 3y = 20'
spectral_r
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
# start
eigenvalues = np.linalg.eigvals(a)
spectral_r = np.max(np.abs(eigenvalues))
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
# start
eigenvalues = np.linalg.eigvals(a)
return np.max(np.abs(eigenvalues))
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
# start
eig_val = np.linalg.eigvals(a)
return np.max(np.abs(eig_val))
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
# begin
eigenvalues = np.linalg.eigvals(a)
spectral_radius = np.max(np.abs(eigenvalues))
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
# start
eigenvalues = np.linalg.eigvals(a)
spectral_r = np.max(np.abs(eigenvalues))
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
find_peaks
import numpy as np
import scipy
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
import numpy as np
import scipy
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
# Find the peaks
peaks, _ = scipy.signal.find_peaks(abs_spectrum[:, 1], height=0)
# Find the indices of the `npeaks` highest peaks
highest_peak_indices = peaks[np.argsort(abs_spectrum[peaks, 1])][-npeaks:]
# Return the wavenumbers of those peaks
return abs_spectrum[highest_peak_indices, 0]
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
Success
import numpy as np
import scipy
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
# Find the peaks
peaks, _ = scipy.signal.find_peaks(abs_spectrum[:,1], height=0)
# Sort the peaks by height
peaks = peaks[np.argsort(abs_spectrum[peaks,1])[::-1]]
# Return the top `npeaks` peaks
return peaks[:npeaks]
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
Success
import numpy as np
import scipy
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
# Find the peaks
peaks, _ = scipy.signal.find_peaks(abs_spectrum[:, 1], height=0)
# Sort the peaks by height
peak_heights = abs_spectrum[peaks, 1]
sorted_peak_indices = np.argsort(peak_heights)[::-1]
# Return the wavenumbers of the highest peaks
return abs_spectrum[peaks[sorted_peak_indices[:npeaks]], 0]
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
Success
import numpy as np
import scipy
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
peaks, _ = scipy.signal.find_peaks(abs_spectrum[:,1], height=0)
peak_wavenumbers = abs_spectrum[peaks,0]
peak_wavenumbers = peak_wavenumbers[np.argsort(peak_wavenumbers)]
return peak_wavenumbers[-npeaks:]
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
Success
import numpy as np
import scipy
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
# find the peaks
peaks = scipy.signal.find_peaks_cwt(abs_spectrum[:,1], np.arange(1,10))
# sort the peaks by intensity
peaks = sorted(peaks, key=lambda x: abs_spectrum[x,1], reverse=True)
# return the top `npeaks` peaks
return peaks[:npeaks]
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
Success
speed_of_sound
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314 # J/mol/K
return math.sqrt(gamma*R*T/m)
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314
return math.sqrt(gamma*R*T/m)
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314 # J/mol/K
return math.sqrt(gamma*R*T/m)
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314
return math.sqrt(gamma*R*T/m)
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314 # J/mol/K
return math.sqrt(gamma * R * T / m)
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
substructure
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
# create a molecule from the smiles string
mol = Chem.MolFromSmiles(smiles)
# create a list to store the indices of the entries that contain the substructure
index_list = []
# loop over the molecules in mol_list
for i in range(len(mol_list)):
# if the molecule contains the substructure, add the index to the index list
if mol_list[i].HasSubstructMatch(mol):
index_list.append(i)
# return the index list
return index_list
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
# create query molecule from smiles string
query_mol = Chem.MolFromSmiles(smiles)
# create list to store indices of entries that contain the substructure
indices = []
# loop through mol_list
for i in range(len(mol_list)):
# if the query molecule is a substructure of the current molecule
if mol_list[i].HasSubstructMatch(query_mol):
# add the index to the list
indices.append(i)
# return the list of indices
return indices
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
# create a molecule object from the smiles string
mol = Chem.MolFromSmiles(smiles)
# create a query object from the molecule object
query = Chem.MolFromSmiles(Chem.MolToSmiles(mol))
# create a list to store the indices of the entries that contain the substructure
indices = []
# loop through the mol_list
for i in range(len(mol_list)):
# if the mol_list entry contains the substructure, add the index to the indices list
if mol_list[i].HasSubstructMatch(query):
indices.append(i)
# return the indices list
return indices
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
# create a molecule from the smiles string
query_mol = Chem.MolFromSmiles(smiles)
# create a list to store the indices of the matching molecules
matching_mols = []
# loop through the molecules in mol_list
for i in range(len(mol_list)):
# if the query molecule is a substructure of the current molecule
if mol_list[i].HasSubstructMatch(query_mol):
# add the index of the current molecule to the list of matching molecules
matching_mols.append(i)
# return the list of matching molecules
return matching_mols
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
# create a molecule from the smiles string
mol = Chem.MolFromSmiles(smiles)
# create a list to store the indices of the entries that contain the substructure
indices = []
# loop over the molecules in mol_list
for i in range(len(mol_list)):
# if the molecule contains the substructure, add the index to the list
if mol_list[i].HasSubstructMatch(mol):
indices.append(i)
# return the list of indices
return indices
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
tanimoto
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
# initialize matrix
tanimoto_matrix = np.zeros((len(smiles_list), len(smiles_list)))
# generate ECFP4 fingerprints
fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(Chem.MolFromSmiles(smiles), 2, nBits=bits) for smiles in smiles_list]
# calculate pairwise Tanimoto similarity
for i in range(len(fps)):
for j in range(len(fps)):
tanimoto_matrix[i, j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
return tanimoto_matrix
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
# initialize empty matrix
tanimoto_matrix = np.zeros((len(smiles_list), len(smiles_list)))
# generate ECFP4 fingerprints
fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(Chem.MolFromSmiles(smile), 2, nBits=bits) for smile in smiles_list]
# calculate Tanimoto similarity
for i in range(len(fps)):
for j in range(i, len(fps)):
tanimoto_matrix[i, j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
tanimoto_matrix[j, i] = tanimoto_matrix[i, j]
return tanimoto_matrix
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
# initialize empty matrix
tanimoto_matrix = np.zeros((len(smiles_list), len(smiles_list)))
# generate ECFP4 fingerprints
fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(Chem.MolFromSmiles(smile), 2, nBits=bits) for smile in smiles_list]
# calculate Tanimoto similarity
for i in range(len(smiles_list)):
for j in range(len(smiles_list)):
tanimoto_matrix[i,j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
return tanimoto_matrix
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
# initialize fingerprint matrix
fp_matrix = np.zeros((len(smiles_list), bits))
# initialize tanimoto similarity matrix
tanimoto_matrix = np.zeros((len(smiles_list), len(smiles_list)))
# loop over smiles list
for i, smiles in enumerate(smiles_list):
# generate molecule from smiles
mol = Chem.MolFromSmiles(smiles)
# generate fingerprint
fp = rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, 2, nBits=bits)
# convert fingerprint to numpy array
arr = np.zeros((1,))
DataStructs.ConvertToNumpyArray(fp, arr)
# store fingerprint in matrix
fp_matrix[i, :] = arr
# calculate pairwise tanimoto similarity
for i in range(len(smiles_list)):
for j in range(len(smiles_list)):
tanimoto_matrix[i, j] = DataStructs.FingerprintSimilarity(fp_matrix[i, :], fp_matrix[j, :])
# return tanimoto similarity matrix
return tanimoto_matrix
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
'numpy.ndarray' object has no attribute 'GetNumBits'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
# initialize empty matrix
tanimoto_matrix = np.zeros((len(smiles_list), len(smiles_list)))
# generate ECFP4 fingerprints
fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(Chem.MolFromSmiles(smile), 2, nBits=bits) for smile in smiles_list]
# calculate Tanimoto similarity
for i in range(len(smiles_list)):
for j in range(len(smiles_list)):
tanimoto_matrix[i,j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
return tanimoto_matrix
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
Success
unbdistance
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
# get the indices of the ligand
lig_ind = traj.topology.select('resname '+lig_str)
# get the indices of the protein
prot_ind = traj.topology.select('protein')
# get the center of mass of the ligand
lig_com = md.compute_center_of_mass(traj.atom_slice(lig_ind))
# get the center of mass of the protein
prot_com = md.compute_center_of_mass(traj.atom_slice(prot_ind))
# get the distance between the two centers of mass
dist = md.compute_distances(traj,lig_com,prot_com)
# return the distance
return dist
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
# get residue indices of ligand
lig_indices = traj.topology.select('resname '+lig_str)
# get center of mass of ligand
lig_com = md.compute_center_of_mass(traj.atom_slice(lig_indices))
# get center of mass of protein
prot_com = md.compute_center_of_mass(traj.atom_slice(traj.topology.select('protein')))
# compute distances between center of mass of protein and ligand
distances = md.compute_distances(traj,lig_com,prot_com)
return distances
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
# get the index of the ligand
lig_ind = traj.topology.select('resname '+lig_str)
# get the index of the protein
prot_ind = traj.topology.select('protein')
# get the center of mass of the ligand
lig_com = md.compute_center_of_mass(traj.atom_slice(lig_ind))
# get the center of mass of the protein
prot_com = md.compute_center_of_mass(traj.atom_slice(prot_ind))
# get the distance between the two
dist = md.compute_distances(traj,lig_com,prot_com)
# return the distance
return dist
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
# Get the indices of the ligand
lig_ind = traj.topology.select('resname '+lig_str)
# Get the indices of the protein
prot_ind = traj.topology.select('protein')
# Get the center of mass of the ligand
lig_com = md.compute_center_of_mass(traj.atom_slice(lig_ind))
# Get the center of mass of the protein
prot_com = md.compute_center_of_mass(traj.atom_slice(prot_ind))
# Compute the distance between the two centers of mass
dist = md.compute_distances(traj,lig_com,prot_com)
# Return the list of distances
return dist
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
# get the indices of the ligand
lig_ind = traj.topology.select('resname '+lig_str)
# get the indices of the protein
prot_ind = traj.topology.select('protein')
# get the center of mass of the ligand
lig_com = md.compute_center_of_mass(traj.atom_slice(lig_ind))
# get the center of mass of the protein
prot_com = md.compute_center_of_mass(traj.atom_slice(prot_ind))
# get the distance between the two
dist = md.compute_distances(traj,lig_com,prot_com)
return dist
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here made it here ## Test Report ### Global Parameters * Engine = incoder/facebook/incoder-1B * T = 0.2
| Test | Run 0 | Run 1 | Run 2 | Run 3 | Run 4 |
|---|---|---|---|---|---|
| aa_polarity | Fail | Fail | Fail | Fail | Fail |
| adiabatic_expansion | Fail | Fail | Fail | Fail | Fail |
| alignment | Fail | Fail | Fail | Fail | Fail |
| angle | Pass | Pass | Pass | Pass | Pass |
| aromatic_aa | Fail | Fail | Fail | Fail | Fail |
| arrhenius | Fail | Fail | Fail | Fail | Fail |
| bimolecular | Fail | Fail | Pass | Pass | Fail |
| bb_rad | Fail | Fail | Fail | Fail | Fail |
| blast | Fail | Fail | Fail | Fail | Fail |
| bravais | Fail | Fail | Fail | Fail | Fail |
| canonicalize | Pass | Pass | Pass | Pass | Pass |
| carnot_efficiency | Fail | Fail | Fail | Fail | Fail |
| claussius | Fail | Fail | Fail | Fail | Fail |
| compare_electronegativity | Fail | Fail | Fail | Fail | Fail |
| condiff_1d | Pass | Pass | Pass | Pass | Pass |
| cubes | Fail | Fail | Fail | Fail | Fail |
| de_broglie | Pass | Fail | Fail | Fail | Fail |
| derivative1d-ch | Fail | Fail | Fail | Fail | Fail |
| derivative_2deg | Fail | Fail | Fail | Fail | Fail |
| descriptors | Fail | Fail | Fail | Fail | Fail |
| dipole | Fail | Fail | Fail | Fail | Fail |
| dou | Fail | Fail | Fail | Fail | Fail |
| eigen-ch | Fail | Fail | Fail | Fail | Fail |
| eigen | Pass | Fail | Fail | Fail | Fail |
| element_mass | Fail | Fail | Fail | Fail | Fail |
| element_name | Fail | Fail | Fail | Fail | Fail |
| energy_of_e | Fail | Fail | Fail | Fail | Fail |
| find_indices | Fail | Fail | Fail | Fail | Fail |
| force_constant | Fail | Fail | Fail | Fail | Fail |
| fourier_1d | Fail | Fail | Fail | Fail | Fail |
| freezing_depression | Fail | Fail | Fail | Fail | Fail |
| genpos | Fail | Fail | Fail | Fail | Fail |
| heating_water | Fail | Fail | Pass | Fail | Fail |
| hydrophobic_res | Fail | Fail | Fail | Fail | Fail |
| ideal_gas | Fail | Fail | Fail | Fail | Fail |
| integral | Fail | Fail | Fail | Fail | Fail |
| trap | Fail | Fail | Fail | Fail | Fail |
| invert_matrix | Fail | Fail | Fail | Fail | Fail |
| iupac2smiles | Fail | Fail | Fail | Fail | Fail |
| kld | Fail | Fail | Fail | Fail | Fail |
| langevin_dynamics | Fail | Fail | Fail | Fail | Fail |
| weighted-least-squares | Fail | Fail | Fail | Fail | Fail |
| lipinski_rule_of_five | Fail | Fail | Fail | Fail | Fail |
| mape | Fail | Fail | Fail | Fail | Fail |
| mapping_operator | Fail | Fail | Fail | Fail | Fail |
| matpow | Fail | Fail | Fail | Fail | Fail |
| matrix_factorial | Fail | Fail | Fail | Fail | Fail |
| max-boltz | Fail | Fail | Fail | Fail | Fail |
| michaelis | Fail | Fail | Fail | Fail | Fail |
| mol_charge | Pass | Pass | Pass | Pass | Pass |
| net_charge | Fail | Fail | Fail | Fail | Fail |
| solve_ode | Fail | Fail | Fail | Fail | Fail |
| ohe | Fail | Fail | Fail | Fail | Fail |
| osmotic_pressure | Fail | Fail | Fail | Fail | Fail |
| pair_wise | Fail | Fail | Fail | Fail | Fail |
| pi | Fail | Fail | Fail | Fail | Fail |
| pib_1d | Fail | Fail | Fail | Fail | Fail |
| pred_interval | Fail | Fail | Fail | Fail | Fail |
| pubchem | Fail | Fail | Fail | Fail | Fail |
| pyscf_energy | Fail | Fail | Fail | Fail | Fail |
| qed | Fail | Fail | Fail | Fail | Fail |
| quantile | Fail | Fail | Fail | Fail | Fail |
| random_walk | Fail | Fail | Fail | Fail | Fail |
| rank | Fail | Fail | Fail | Fail | Fail |
| remove-water | Fail | Fail | Fail | Fail | Fail |
| rms_velocity | Fail | Fail | Fail | Fail | Fail |
| rmse | Fail | Fail | Fail | Fail | Fail |
| rog | Fail | Fail | Fail | Fail | Fail |
| sasa | Fail | Fail | Fail | Fail | Fail |
| scaffold | Fail | Fail | Fail | Fail | Fail |
| seq-align | Fail | Fail | Fail | Fail | Fail |
| seq-trans | Fail | Fail | Fail | Fail | Fail |
| sequence | Fail | Fail | Fail | Fail | Fail |
| sle | Fail | Fail | Fail | Fail | Fail |
| spectral_r | Fail | Fail | Fail | Fail | Fail |
| find_peaks | Fail | Fail | Fail | Fail | Fail |
| speed_of_sound | Fail | Fail | Fail | Fail | Fail |
| substructure | Fail | Fail | Fail | Fail | Fail |
| tanimoto | Fail | Fail | Fail | Fail | Fail |
| unbdistance | Fail | Fail | Fail | Fail | Fail |
aa_polarity
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
[insert]
return countimport math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for x in sequence:
if x == 'N':
count += 1
return count
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for x in sequence:
if x == 'P':
count += 1
return count
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for x in sequence:
if x == 'P':
count += 1
return count
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for char in sequence:
if char == 'P':
count += 1
return count
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for char in sequence:
if char == 'P':
count += 1
return count
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
adiabatic_expansion
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
[insert]
return T2
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1 + P1*math.exp(-gamma*T1)
T2 = T2 + P2*math.exp(-gamma*T2)
if __name__ == "__main__":
T1 = float(sys.argv[1])
P1 = float(sys.argv[2])
P2 = float(sys.argv[3])
gamma = float(sys.argv[4])
print cooling(T1,P1,P2,gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 17)
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1 + gamma*((P2-P1)/(T1-T2))
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
local variable 'T2' referenced before assignment
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1 + gamma*P1*P2*(math.exp((P2-P1)/T1))
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1 + gamma * (P2-P1)
300 else 300
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
unindent does not match any outer indentation level (<string>, line 10)
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1 + gamma * P1
T3 = T2 + gamma * P2
T4 = T3
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
alignment
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
[insert]
return trajimport mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj = md.load(traj)
traj = traj.select([frame_index])
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
expected str, bytes or os.PathLike object, not Trajectory
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj = md.load(traj)
traj = md.AlignTraj(traj, frame_index)
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
expected str, bytes or os.PathLike object, not Trajectory
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj = md.load(traj)
traj.select_atoms("resname *" + frame_index)
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
expected str, bytes or os.PathLike object, not Trajectory
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj = md.load(traj)
traj = md.AlignTraj(traj)
traj = md.AlignTraj(traj, frame_index)
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
expected str, bytes or os.PathLike object, not Trajectory
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj = md.load(traj)
traj.align(frame_index)
|/
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
invalid syntax (<string>, line 13)
angle
import numpy as np
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
[insert]
return angleimport numpy as np
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
angle = np.arccos(np.dot(v1,v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)))
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
angle = np.arccos(np.dot(v1,v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)))
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
angle = np.arccos(np.dot(v1,v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)))
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
angle = np.arccos(np.dot(v1,v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)))
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
angle = np.arccos(np.dot(v1,v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)))
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
aromatic_aa
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
[insert]
return countimport math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
count = 0
for x in sequence:
if x == 'A' or x == 'a':
count += 1
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
count = 0
for x in sequence:
if x == 'A':
count += 1
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
count = 0
for letter in sequence:
if letter == 'A':
count += 1
return count
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
count = 0
for x in sequence:
if x in "ACGT":
count += 1
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
count = 0
for letter in sequence:
if letter == 'A':
count += 1
return count
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
arrhenius
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
[insert]
return k1import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = math.sqrt(T2/T1)
k2 = k1/(math.pow(T1,2)/math.pow(T2,2))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = (T2/T1)**(k2/2)
k2 = k1/(math.sqrt(2*math.pi)*Ea)
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = (T2/T1)*((T2/T1)**2 - Ea**2)
k2 = k1/(T2/T1)
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = (T2/T1)**(k2/2)
k2 = k1/(math.exp((k2/2)/Ea))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = (T2/T1)**(k2/2)
k2 = k1/(1+k1/Ea)
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
bimolecular
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
[insert]
return rateimport math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*A*B
|/
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
invalid syntax (<string>, line 14)
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = 0
for x in range(0,k):
rate += A*math.pow(B*math.pow(math.log(x/k),2),2)
if __name__ == "__main__":
print bimolecular_rate(2,1,2)
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
invalid syntax (<string>, line 17)
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*A*B
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*A*B
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*A*B
|/
|/
|/
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
invalid syntax (<string>, line 14)
bb_rad
import numpy as np
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
[insert]
return Bimport numpy as np
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
B = (lam**2 - T)/(lam**2 + T)
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
B = (lam**2 - T**2) / (lam**2 - T**2 - lam*T*T)
B = B * T
|/
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 12)
import numpy as np
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
B = (lam**2 - T**2)/(lam**2 - T**2 - lam*T)
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
B = (lam**2 - T)/(lam**2 + T)
B = B**0.5
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
B = (lam**2 - T**2) / (lam**2 - T**2)
B = B * T
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
blast
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
[insert]
return e, idimport requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
seq = str(seq)
seq = str(seq).upper()
seq = str(seq).replace(' ','')
seq = str(seq).replace('\n','')
seq = str(seq).replace('\r','')
seq = str(seq).replace('\t','')
seq = str(seq).replace(' ','')
seq = str(seq).replace('\n','')
seq = str(seq).replace('\r','')
seq = str(seq).replace('\t','')
seq = str(seq).replace(' ','')
seq = str(seq).replace('\n','')
seq = str(seq).replace('\r','')
seq = str(seq).replace('\t','')
seq = str(seq).replace(' ','')
seq = str(seq).replace('\n','')
seq = str(seq).replace('\r','')
seq = str(seq).replace('\t','')
seq = str(seq).replace(' ','')
seq = str(seq).replace('\n','')
seq = str(seq).replace('\r','')
seq = str(seq).replace('\t','')
seq = str(seq).replace(' ','')
seq = str(seq).replace('\n','')
seq = str(seq).replace('\r','')
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
name 'e' is not defined
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
seq = str(seq)
seq = str(seq.upper())
seq = str(seq.lower())
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
name 'e' is not defined
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
name 'e' is not defined
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
seq = str(seq)
seq = str(seq).upper()
seq = str(seq).replace(' ','')
seq = str(seq).replace('\n','')
seq = str(seq).replace('\r','')
seq = str(seq).replace('\t','')
seq = str(seq).replace(',','')
seq = str(seq).replace('"','')
seq = str(seq).replace('\'','')
seq = str(seq).replace('"','')
seq = str(seq).replace('\'','')
seq = str(seq).replace('"','')
seq = str(seq).replace('\'','')
seq = str(seq).replace('"','')
seq = str(seq).replace('\'','')
seq = str(seq).replace('"','')
seq = str(seq).replace('\'','')
seq = str(seq).replace('"','')
seq = str(seq).replace('\'','')
seq = str(seq).replace('"','')
seq = str(seq).replace('\'','')
seq = str(seq).replace('"','')
seq = str(seq).replace('\'','')
seq = str(seq).replace('"','')
seq = str(seq).replace('\'','')
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
name 'e' is not defined
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
seq = str(seq)
seq = str(seq.upper())
seq = str(seq.lower())
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
name 'e' is not defined
bravais
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
[insert]
return nameimport math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
group_number = int(group_number)
group_number = math.floor(group_number)
group_number = group_number - 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 4
group_number = group_number + 1
group_number = group_number % 8
group_number = group_number + 1
group_number = group_number % 16
group_number = group_number + 1
group_number = group_number % 32
group_number = group_number + 1
group_number = group_number % 64
group_number = group_number + 1
group_number = group_number % 128
group_number = group_number + 1
group_number = group_number % 256
group_number = group_number + 1
group_number = group_number % 512
group_number = group_number + 1
group_number = group_number % 1024
group_number = group_number + 1
group_number = group_number % 2048
group_number = group_number + 1
group_number = group_number % 4096
group_number = group_number + 1
group_number = group_number % 8192
group_number = group_number + 1
group_number = group_number % 16384
group_number = group_number + 1
group_number = group_number % 32768
group_number = group_number + 1
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
name 'name' is not defined
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
group_number = int(group_number)
lattice = {
0: 'X',
1: 'Y',
2: 'Z',
3: 'A',
4: 'B',
5: 'C',
6: 'D',
7: 'E',
8: 'F',
9: 'G',
10: 'H',
11: 'I',
12: 'J',
13: 'K',
14: 'L',
15: 'M',
16: 'N',
17: 'O',
18: 'P',
19: 'Q',
20: 'R',
21: 'S',
22: 'T',
23: 'U',
24: 'V',
25: 'W',
26: 'X',
27: 'Y',
28: 'Z',
29: 'A',
30: 'B',
31: 'C',
32: 'D',
33: 'E',
34: 'F',
35: 'G',
36: 'H',
37: 'I',
38: 'J',
39: 'K',
40: 'L',
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
invalid syntax (<string>, line 54)
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
group_number = int(group_number)
if group_number 1:
raise ValueError("group_number must be greater than 0")
group_number = math.floor(group_number)
group_number = group_number - 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % group_number
group_number = group_number + 1
group_number = group_number % group_number
group_number = group_number + 1
group_number = group_number % group_number
group_number = group_number + 1
group_number = group_number % group_number
group_number = group_number + 1
group_number = group_number % group_number
group_number = group_number + 1
group_number = group_number % group_number
group_number = group_number + 1
group_number = group_number % group_number
group_number = group_number + 1
group_number = group_number % group_number
group_number = group_number + 1
group_number = group_number % group_number
group_number = group_number + 1
group_number = group_number % group_number
group_number = group_number + 1
group_number = group_number % group_number
group_number = group_number + 1
group_number = group_number % group_number
group_number = group_number + 1
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
invalid syntax (<string>, line 11)
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
group_number = int(group_number)
lattice = group_number - 1
lattice_letters = [
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z",
]
lattice_letters_reversed = [
letter[::-1] for letter in lattice_letters
]
lattice_letters_reversed.reverse()
lattice_letters_reversed = "".join(lattice_letters_reversed)
lattice_letters_reversed = lattice_letters_reversed.upper()
lattice_letters_reversed = lattice_letters_reversed.replace("_", "")
lattice_letters_reversed = lattice_letters_reversed.replace("L", "")
lattice_letters_reversed = lattice_letters_reversed.replace("M", "")
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
name 'name' is not defined
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
group_number = int(group_number)
9:
raise ValueError("Invalid group number")
group_number = group_number - 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
unindent does not match any outer indentation level (<string>, line 11)
canonicalize
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
[insert]
return canon_listimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canonical_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canonical_list.append(Chem.MolToSmiles(mol))
return canonical_list
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canon_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canonical_smiles = Chem.MolToSmiles(mol)
canon_list.append(canonical_smiles)
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canonical_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canonical_list.append(Chem.MolToSmiles(mol))
return canonical_list
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canon_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canonical_smiles = Chem.MolToSmiles(mol, canonical=True)
canon_list.append(canonical_smiles)
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canon_list = []
for smi in smiles_list:
mol = Chem.MolFromSmiles(smi)
canonical_smiles = Chem.MolToSmiles(mol, canonical=True)
canon_list.append(canonical_smiles)
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
carnot_efficiency
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
[insert]
return eps
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = T_hot / T_cold
1:
eps = eps
if eps 1:
eps = 1
return eps
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
unindent does not match any outer indentation level (<string>, line 10)
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = math.sqrt((T_hot / T_cold) ** 2 + (T_hot / T_cold) ** 2)
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = math.pow(T_hot / T_cold, 2)
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = T_hot / T_cold
eps = math.pow(eps, 2)
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = math.sqrt((T_hot / T_cold) ** 2 + (T_hot / T_hot) ** 2)
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
claussius
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
[insert]
return P2
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = HVap*T2/(T1+T2)
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = P1/(HVap*T2)
P2 = P2*(T2-T1)
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = P1 + (HVap - T1) * (T2 - T1)
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = P1 + HVap * math.exp(-(T2 - T1)/T1)
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = P1 + HVap * math.exp(-(T2 - T1)/T1)
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
compare_electronegativity
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
[insert]
return resultimport math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
electronegativity = mendeleev.Electronegativity(element1)
result = False
electronegativity:
result = True
else:
result = False
return result
if __name__ == "__main__":
print compare_electronegativity("C","C")
print compare_electronegativity("C","C")
print compare_electronegativity("C","C")
print compare_electronegativity("C","C")
print compare_electronegativity("C","C")
print compare_electronegativity("C","C")
return result
result = True if compare_electronegativity("O","C") else FalseOutput:
unindent does not match any outer indentation level (<string>, line 12)
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
electronegativity = mendeleev.electronegativity(element1,element2)
0.0
return result
result = True if compare_electronegativity("O","C") else FalseOutput:
unindent does not match any outer indentation level (<string>, line 11)
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
electronegativity = mendeleev.electronegativity(element1,element2)
mendeleev.electronegativity(element2,element1)
return result
result = True if compare_electronegativity("O","C") else FalseOutput:
unindent does not match any outer indentation level (<string>, line 11)
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
electronegativity = mendeleev.electronegativity(element1,element2)
0.0:
return True
else:
return False
return result
result = True if compare_electronegativity("O","C") else FalseOutput:
unindent does not match any outer indentation level (<string>, line 11)
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
result = mendeleev.compare(element1,element2)
return result
result = True if compare_electronegativity("O","C") else FalseOutput:
module 'mendeleev' has no attribute 'compare'
condiff_1d
import numpy as np
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
[insert]
return diffimport numpy as np
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.diff(x)
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.diff(x)
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.diff(x)
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.diff(x)
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.diff(x)
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
cubes
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
[insert]
return simport math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = n
for i in range(1, n+1):
s *= i
return s
return s
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = n * n * n
for i in range(1, n+1):
s *= i
return s
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = n
for i in range(1, int(math.sqrt(n))+1):
s += i
return s
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = n
for i in range(2, int(math.sqrt(n))+1):
s *= i
return s
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = n
for i in range(1, n+1):
s *= i
return s
return s
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
de_broglie
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
[insert]
return limport math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
l = m*math.pow(10,-(v/10))
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
l=math.sqrt(m*m+v*v)
|/
|/
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 16)
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
l=math.sqrt(m*m+v*v)
|/
|/
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 14)
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
l=math.sqrt(m*m+v*v)
|/
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 14)
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
l=math.sqrt(m*m+v*v)
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
derivative1d-ch
import numpy as np
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
[insert]
return dimport numpy as np
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
dx=(b-c)*(x-a)/(a+b+c)
return dx
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
dx=(b-a)
dy=(c-x)
|/
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
invalid syntax (<string>, line 13)
import numpy as np
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
dx=(b-c)*(x-a)
dy=(b-c)*(x-a)
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
name 'd' is not defined
import numpy as np
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
dx=(b-c)*(x-a)/(a+b)
dy=(b-c)*(x-c)/(a+b)
dz=(b-c)*(x-c)/(a+b)
|/
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
invalid syntax (<string>, line 14)
import numpy as np
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
dx=(b-a)/(c*x)
|/d
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
invalid syntax (<string>, line 14)
derivative_2deg
import numpy as np
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
[insert]
return derivimport numpy as np
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = np.poly1d(np.polyfit(x,y,2))
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
name 'y' is not defined
import numpy as np
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = np.poly1d(np.polyfit(x,y,2))
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
name 'y' is not defined
import numpy as np
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = np.poly1d([a,b,c])
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = np.poly1d(np.polyfit(x,y,2))
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
name 'y' is not defined
import numpy as np
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = np.poly1d(np.polyfit(x,y,2))
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
name 'y' is not defined
descriptors
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
[insert]
return descriptorsimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smi in smiles_list:
mol = Chem.MolFromSmiles(smi)
descriptors.append(rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, radius=3, nBits=2048))
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smi in smiles_list:
mol = Chem.MolFromSmiles(smi)
descriptors.append(Descriptors.MolDescriptors.GetMorganFingerprintAsBitVect(mol))
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
module 'rdkit.Chem.Descriptors' has no attribute 'MolDescriptors'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smi in smiles_list:
mol = Chem.MolFromSmiles(smi)
descriptors.append(rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, radius=3, nBits=2048))
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smi in smiles_list:
mol = Chem.MolFromSmiles(smi)
descriptors.append(Descriptors.MolDescriptors.GetMorganFingerprintAsBitVect(mol))
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
module 'rdkit.Chem.Descriptors' has no attribute 'MolDescriptors'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smi in smiles_list:
mol = Chem.MolFromSmiles(smi)
descriptors.append(rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, radius=4, useFeatures=False))
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
dipole
import numpy as np
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
[insert]
return dipole_momentimport numpy as np
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
i', charges, coordinates)
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
EOL while scanning string literal (<string>, line 11)
import numpy as np
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole_moment = np.zeros(3)
for i in range(3):
dipole_moment[i] = np.power(coordinates[i,0] - charges[i,0], 2) + np.power(coordinates[i,1] - charges[i,1], 2) + np.power(coordinates[i,2] - charges[i,2], 2)
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
too many indices for array: array is 1-dimensional, but 2 were indexed
import numpy as np
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole = np.zeros((len(coordinates), 3))
for i in range(len(coordinates)):
dipole[i,0] = coordinates[i][0]
dipole[i,1] = coordinates[i][1]
dipole[i,2] = charges[i]
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
unsupported operand type(s) for -: 'float' and 'function'
import numpy as np
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
i', charges, coordinates)
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
EOL while scanning string literal (<string>, line 11)
import numpy as np
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
i', charges, coordinates)
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
EOL while scanning string literal (<string>, line 11)
dou
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
[insert]
return dimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
bonds = mol.GetBonds()
bonds = [b for b in bonds if b.GetBeginAtomIdx() == b.GetEndAtomIdx()]
bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.SINGLE]
bonds = [b for b in bonds if b.GetBeginAtomIdx() not in [b.GetEndAtomIdx(), b.GetBeginAtomIdx()+1]]
bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.DOUBLE]
bonds = [b for b in bonds if b.GetBeginAtomIdx() not in [b.GetEndAtomIdx(), b.GetBeginAtomIdx()+1]]
bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.TRIPLE]
bonds = [b for b in bonds if b.GetBeginAtomIdx() not in [b.GetEndAtomIdx(), b.GetBeginAtomIdx()+1]]
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
name 'd' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
bonds = mol.GetBonds()
bonds = [b for b in bonds if b.GetBeginAtomIdx() == b.GetEndAtomIdx()]
bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.SINGLE]
bonds = [b for b in bonds if b.GetBeginAtomIdx()!= b.GetEndAtomIdx()]
bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.DOUBLE]
bonds = [b for b in bonds if b.GetBeginAtomIdx()!= b.GetEndAtomIdx()]
bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.TRIPLE]
bonds = [b for b in bonds if b.GetBeginAtomIdx()!= b.GetEndAtomIdx()]
bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.AROMATIC]
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
name 'd' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
name 'd' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
name 'd' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
bonds = mol.GetBonds()
bondCount = len(bonds)
bondHash = rdMolHash.MolHash(bonds)
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
Python argument types in
rdkit.Chem.rdMolHash.MolHash(_ROBondSeq)
did not match C++ signature:
MolHash(RDKit::ROMol mol, RDKit::MolHash::HashFunction func)
eigen-ch
import numpy as np
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w, v = np.linalg.eig(M)
|/v
|/
|/
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
invalid syntax (<string>, line 11)
import numpy as np
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w, v = np.linalg.eig(M)
|/
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
invalid syntax (<string>, line 13)
import numpy as np
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w, v = np.linalg.eig(M)
|/
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
invalid syntax (<string>, line 13)
import numpy as np
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w, v = np.linalg.eig(M)
|/
|/
|/
|/
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
invalid syntax (<string>, line 15)
import numpy as np
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w, v = np.linalg.eig(M)
|/
|/
|/
|/
|/
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
invalid syntax (<string>, line 15)
eigen
import numpy as np
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
[insert]
return w,vimport numpy as np
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w, v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w, v = np.linalg.eig(M)
|/
|/
|/
|/
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
invalid syntax (<string>, line 13)
import numpy as np
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w, v = np.linalg.eig(M)
|/
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
invalid syntax (<string>, line 25)
import numpy as np
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w, v = np.linalg.eig(M)
|/ file dstars=0
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
invalid syntax (<string>, line 11)
import numpy as np
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w, v = np.linalg.eig(M)
|/
|/
|/
|/
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
invalid syntax (<string>, line 13)
element_mass
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
[insert]
return massimport math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.mass(element_symbol)
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
module 'mendeleev' has no attribute 'mass'
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.ElementMass(element_symbol)
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
module 'mendeleev' has no attribute 'ElementMass'
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.elements.get_mass(element_symbol)
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
module 'mendeleev.elements' has no attribute 'get_mass'
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.ElementMass(element_symbol)
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
module 'mendeleev' has no attribute 'ElementMass'
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.ElementMass(element_symbol)
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
module 'mendeleev' has no attribute 'ElementMass'
element_name
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
[insert]
return simport math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.symbol(element_number)
|/
return s
result = True if symbol(26).lower()=="fe" else FalseOutput:
invalid syntax (<string>, line 13)
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.symbol(element_number)
|/
return s
result = True if symbol(26).lower()=="fe" else FalseOutput:
invalid syntax (<string>, line 13)
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.symbol(element_number)
return s
result = True if symbol(26).lower()=="fe" else FalseOutput:
module 'mendeleev' has no attribute 'symbol'
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.symbol(element_number)
|/
return s
result = True if symbol(26).lower()=="fe" else FalseOutput:
invalid syntax (<string>, line 13)
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.symbol(element_number)
|/
return s
result = True if symbol(26).lower()=="fe" else FalseOutput:
invalid syntax (<string>, line 13)
energy_of_e
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
[insert]
return energyimport math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = 0.0
for i in range(1,n+1):
energy += i
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = 1
for i in range(1, n+1):
energy *= i
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = n * (n + 1)
energy -= n * n * n * n * n
energy -= n * n * n * n * n * n * n
energy -= n * n * n * n * n * n * n * n * n
energy -= n * n * n * n * n * n * n * n * n * n
energy -= n * n * n * n * n * n * n * n * n * n * n
energy -= n * n * n * n * n * n * n * n * n * n * n * n * n
energy -= n * n * n * n * n * n * n * n * n * n * n * n * n * n
energy -= n * n * n * n * n * n * n * n * n * n * n * n * n * n * n * n
energy -= n * n * n * n * n * n * n * n * n * n * n * n * n * n * n * n * n * n
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = 0.
for i in range(1, int(math.sqrt(n))+1):
energy += i * (i-1) * (i-2) * (i-3) * (i-4) * (i-5) * (i-6) * (i-7) * (i-8) * (i-9) * (i-10) * (i-11) * (i-12) * (i-13) * (i-14) * (i-15) * (i-16) * (i-17) * (i-18) * (i-19) * (i-20) * (i-21) * (i-22) * (i-23) * (i-24) * (i-25) * (i-26) * (i-27) * (i-28) * (i-29) * (i-30)
return energy
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = 0.
for i in range(1, int(math.sqrt(n))+1):
energy += i * (n**i)
if __name__ == "__main__":
n = int(sys.argv[1])
energy = energy_of_e(n)
print(energy)
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
'return' outside function (<string>, line 21)
find_indices
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
[insert]
return idximport mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
pdb = md.load(pdb_file)
atoms = pdb.select('CA')
idx = np.where(atoms.resname!= 'CA')[0]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Trajectory' object has no attribute 'select'
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
pdb = md.load(pdb_file)
atoms = pdb.select('CA')
idx = np.where(atoms.select('CA') == True)[0]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Trajectory' object has no attribute 'select'
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
pdb = md.load(pdb_file)
atoms = pdb.select('CA')
idx = np.where(atoms.select('CA') == True)[0]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Trajectory' object has no attribute 'select'
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
pdb = md.load(pdb_file)
atoms = pdb.select('CA')
idx = np.where(atoms.select('CA') == True)[0]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Trajectory' object has no attribute 'select'
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
pdb = md.load(pdb_file)
atoms = pdb.select('CA')
0)[0]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
unindent does not match any outer indentation level (<string>, line 11)
force_constant
import numpy as np
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
[insert]
return kimport numpy as np
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = m1/m2
k = k*wave_len
|/
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 14)
import numpy as np
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = m1/m2
k = k*wave_len
|/
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 14)
import numpy as np
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = m1/m2
k = k*wave_len
|/
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 14)
import numpy as np
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = m1/m2 # reduced mass
k = k*wave_len**2 # wave length in cm^-1 units
|/
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 14)
import numpy as np
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = m1/(m1+m2) * np.exp(-(wave_len/wave_len.value)**2)
|/
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 13)
fourier_1d
import numpy as np
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
[insert]
return wimport numpy as np
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
w = np.fft.fft(x)
|/
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
invalid syntax (<string>, line 11)
import numpy as np
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
w = np.fft.fft(x)
|/
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
invalid syntax (<string>, line 11)
import numpy as np
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
w = np.fft.fft(x)
|/
|/ file dstars=0
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
invalid syntax (<string>, line 11)
import numpy as np
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
w = np.fft.fft(x)
|/
|/ file dstars=0
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
invalid syntax (<string>, line 11)
import numpy as np
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
w = np.fft.fft(x)
|/
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
invalid syntax (<string>, line 11)
freezing_depression
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
[insert]
return deltaTimport math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
KfK = Kf*Kf
deltaT = KfK/math.sqrt(m)
if __name__ == "__main__":
Kf = float(sys.argv[1])
m = float(sys.argv[2])
print freezing_depression(Kf,m)
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
invalid syntax (<string>, line 17)
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
deltaT = Kf*m/(Kf+m)
if deltaT 0:
deltaT = 0
else:
deltaT = math.floor(deltaT)
return deltaT
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
invalid syntax (<string>, line 12)
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
name 'deltaT' is not defined
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
deltaT=Kf*m
if deltaT0:
deltaT=0
return deltaT
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
name 'deltaT0' is not defined
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
KfK = Kf*Kf
deltaT = KfK*m
if deltaT 0:
deltaT = 0
else:
deltaT = deltaT/KfK
return deltaT
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
invalid syntax (<string>, line 13)
genpos
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
[insert]
return generatorsimport requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
generators = []
for i in range(1,11):
url = "http://www.crystallography.com/spacegroups/" + str(gnum) + "/general-positions.aspx"
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
table = soup.find('table')
rows = table.find_all('tr')
generators.append([])
for tr in rows:
cols = tr.find_all('td')
generators[i].append([])
for td in cols:
generators[i][-1].append(td.text)
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
'NoneType' object has no attribute 'find_all'
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
generators = []
base_url = "http://ec.europa.eu/eurostat/eurostat-data/"
page_num = 1
while page_num gnum:
page_url = base_url + str(page_num)
page_response = requests.get(page_url)
page_soup = BeautifulSoup(page_response.text, 'html.parser')
generators.append(page_soup.find_all('table', class_='table')[0])
page_num += 1
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
invalid syntax (<string>, line 16)
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
generators = []
for g in range(1, gnum+1):
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
expected an indented block (<string>, line 13)
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
generators = []
for g in range(1,11):
generators.append(g*gnum)
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
Success
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
generators = []
base_url = 'http://www.internationalcrystallography.com/crystallography/crystallography/'
soup = BeautifulSoup(requests.get(base_url+str(gnum)).text, 'html.parser')
table = soup.find('table', class_='table')
rows = table.find_all('tr')
for row in rows:
cols = row.find_all('td')
generators.append(cols[0].text)
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
HTTPConnectionPool(host='www.internationalcrystallography.com', port=80): Max retries exceeded with url: /crystallography/crystallography/66 (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f76f8c5bd90>: Failed to establish a new connection: [Errno -2] Name or service not known'))
heating_water
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
[insert]
return q
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = 0.0
for j in range(n):
q += (T1 * math.pow(T2, j))
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = 0.0
for j in range(n):
q += (T1 - T2) * (T1 - T2) / ((T1 - T2) * (T1 - T2))
T1 -= T2
T2 -= T2
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = ((T1-T2)/(n*(n-1))) * math.log(T2/T1)
if __name__ == "__main__":
n = int(sys.argv[1])
T1 = float(sys.argv[2])
T2 = float(sys.argv[3])
print heating_energy(n, T1, T2)
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 15)
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = (T1 * n) / (T2 * n)
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
hydrophobic_res
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
[insert]
return residsimport mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
pdb = mdtraj.load(pdb_filename)
resids = []
for model in pdb.models:
for residue in model.residues:
if residue.resname!= 'H':
resids.append(residue.index)
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
name 'mdtraj' is not defined
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
pdb = mdtraj.load(pdb_filename)
resids = []
for model in pdb.models:
for residue in model.residues:
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
expected an indented block (<string>, line 14)
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
pdb = md.load(pdb_filename)
resids = []
for model in pdb.models:
for residue in model.residues:
if residue.resname!= 'H':
resids.append(residue.index)
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
'Trajectory' object has no attribute 'models'
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
pdb = md.load(pdb_filename)
resids = []
for model in pdb.models:
for residue in model.residues:
if residue.resname!= 'HOH':
resids.append(residue.index)
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
'Trajectory' object has no attribute 'models'
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
pdb = mdtraj.load(pdb_filename)
resids = []
for model in pdb.models:
for residue in model.residues:
if residue.resname!= 'H':
resids.append(residue.index)
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
name 'mdtraj' is not defined
ideal_gas
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
[insert]
return Pimport math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
P = V*T*math.exp(-n/2)
P = P*1000
if __name__ == "__main__":
n = int(sys.argv[1])
V = float(sys.argv[2])
T = float(sys.argv[3])
P = ideal_gas_pressure(n,V,T)
print P
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Missing parentheses in call to 'print'. Did you mean print(P)? (<string>, line 18)
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
P = V*math.exp(-T/n)
return P
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
P = V*T/(n*math.pow(10,9))
|/ file dstars=0
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 13)
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
P = V*math.exp(-T/n)
return P
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
P = V*T*math.exp(-n*T/V)
return P
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
integral
import numpy as np
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
[insert]
return integralimport numpy as np
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
integral = np.poly1d([a,b,c,d])
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
Success
import numpy as np
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
integral = np.poly1d([a,b,c,d])
|/
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
invalid syntax (<string>, line 12)
import numpy as np
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
integral = np.poly1d([a,b,c,d])
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
Success
import numpy as np
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
integral = np.poly1d([a,b,c,d])
|/
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
invalid syntax (<string>, line 12)
import numpy as np
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
integral = np.poly1d([a,b,c,d])
|/
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
invalid syntax (<string>, line 12)
trap
import numpy as np
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
[insert]
return integralimport numpy as np
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
integral = 0
for i in range(n):
integral += f(a) * f(b) / i
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
import numpy as np
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
integral = 0
for i in range(n):
integral += f(a) * np.exp(-(b - a) * i)
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
import numpy as np
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
integral = 0
for i in range(n):
integral += f(a) * np.trapz(b - a, a)
return integral
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
diff requires input that is at least one dimensional
import numpy as np
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
integral = 0
for i in range(n):
integral += f(a) * np.exp(-b * i)
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
import numpy as np
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
integral = 0
for i in range(n):
integral += a * (f(a) + f(b))
a, b = b, a + b
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
loop of ufunc does not support argument 0 of type int which has no callable sqrt method
invert_matrix
import numpy as np
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
[insert]
return Ainvimport numpy as np
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
Ainv = np.linalg.inv(A)
|/
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
invalid syntax (<string>, line 12)
import numpy as np
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
Ainv = np.linalg.inv(A)
|/
|/ file dstars=0
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
invalid syntax (<string>, line 12)
import numpy as np
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
Ainv = np.linalg.inv(A)
|/
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
invalid syntax (<string>, line 12)
import numpy as np
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
Ainv = np.linalg.inv(A)
|/
|/ file dstars=1
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
invalid syntax (<string>, line 12)
import numpy as np
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
name 'Ainv' is not defined
iupac2smiles
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
[insert]
return SMILESimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
IUPAC = IUPAC.upper()
IUPAC = IUPAC.replace('-','')
IUPAC = IUPAC.replace('_','')
IUPAC = IUPAC.replace('(','')
IUPAC = IUPAC.replace(')','')
IUPAC = IUPAC.replace(',','')
IUPAC = IUPAC.replace('.','')
IUPAC = IUPAC.replace(';','')
IUPAC = IUPAC.replace(':','')
IUPAC = IUPAC.replace('=','')
IUPAC = IUPAC.replace('!','')
IUPAC = IUPAC.replace('~','')
IUPAC = IUPAC.replace('@','')
IUPAC = IUPAC.replace('#','')
IUPAC = IUPAC.replace('$','')
IUPAC = IUPAC.replace('%','')
IUPAC = IUPAC.replace('^','')
IUPAC = IUPAC.replace('&','')
IUPAC = IUPAC.replace('*','')
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
name 'SMILES' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
SMILES = []
for char in IUPAC:
if char.isupper():
SMILES.append(char)
else:
SMILES.append(char.upper())
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
IUPAC = IUPAC.upper()
IUPAC = IUPAC.replace("-", "")
IUPAC = IUPAC.replace("(", "")
IUPAC = IUPAC.replace(")", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace(":", "")
IUPAC = IUPAC.replace(";", "")
IUPAC = IUPAC.replace(",", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace("(", "")
IUPAC = IUPAC.replace(")", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace(":", "")
IUPAC = IUPAC.replace(";", "")
IUPAC = IUPAC.replace(",", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace("(", "")
IUPAC = IUPAC.replace(")", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace(":", "")
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
name 'SMILES' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
IUPAC = IUPAC.upper()
IUPAC = IUPAC.replace("-", "")
IUPAC = IUPAC.replace("(", "")
IUPAC = IUPAC.replace(")", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace(":", "")
IUPAC = IUPAC.replace(";", "")
IUPAC = IUPAC.replace(",", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace("(", "")
IUPAC = IUPAC.replace(")", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace(":", "")
IUPAC = IUPAC.replace(";", "")
IUPAC = IUPAC.replace(",", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace("(", "")
IUPAC = IUPAC.replace(")", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace(":", "")
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
name 'SMILES' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
IUPAC = IUPAC.upper()
IUPAC = IUPAC.replace("-", "")
IUPAC = IUPAC.replace("(", "")
IUPAC = IUPAC.replace(")", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace(":", "")
IUPAC = IUPAC.replace(",", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace("(", "")
IUPAC = IUPAC.replace(")", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace(":", "")
IUPAC = IUPAC.replace(",", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace("(", "")
IUPAC = IUPAC.replace(")", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace(":", "")
IUPAC = IUPAC.replace(",", "")
IUPAC = IUPAC.replace("'", "")
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
name 'SMILES' is not defined
kld
import numpy as np
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
[insert]
return lossimport numpy as np
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = 0
for i in range(len(true_data)):
loss += np.log(np.linalg.norm(true_data[i] - predicted_data[i]))
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
Success
import numpy as np
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = 0
for i in range(len(true_data)):
loss += np.log(np.linalg.norm(true_data[i] - predicted_data[i]))
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
Success
import numpy as np
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = 0
for i in range(len(true_data)):
loss += np.log(np.linalg.norm(true_data[i] - predicted_data[i]))
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
Success
import numpy as np
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = 0.0
for i in range(len(true_data)):
loss += (true_data.data[i]-predicted_data.data[i])**2
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
Success
import numpy as np
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = 0
for i in range(len(true_data)):
loss += np.log(np.linalg.norm(true_data[i] - predicted_data[i]))
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
Success
langevin_dynamics
import numpy as np
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
[insert]
return x_traj, v_trajimport numpy as np
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(1,n_steps):
x_traj[i] = x_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma,T)
v_traj[i] = v_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma,T)
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
F() takes from 1 to 2 positional arguments but 4 were given
import numpy as np
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(1,n_steps):
x_traj[i] = x_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma,T)
v_traj[i] = v_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma,T)
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
F() takes from 1 to 2 positional arguments but 4 were given
import numpy as np
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(1,n_steps):
x_traj[i] = x_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma,T)
v_traj[i] = v_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma,T)
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
F() takes from 1 to 2 positional arguments but 4 were given
import numpy as np
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(1,n_steps):
x_traj[i] = x_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma,T)
v_traj[i] = v_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma,T)
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
F() takes from 1 to 2 positional arguments but 4 were given
import numpy as np
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(1,n_steps):
x_traj[i] = x_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma,T)
v_traj[i] = v_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma,T)
x_traj[-1] = x0
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
F() takes from 1 to 2 positional arguments but 4 were given
weighted-least-squares
import numpy as np
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
[insert]
return betaimport numpy as np
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
beta = np.dot(x.T, np.dot(w, x))
|/
|/
|/
|/
|/
|/
|/
|/
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
invalid syntax (<string>, line 10)
import numpy as np
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
beta = np.linalg.lstsq(x, y, w)[0]
|/
|/
|/
|/
|/
|/
|/
|/
|/
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
invalid syntax (<string>, line 10)
import numpy as np
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
beta = np.dot(x.T, np.dot(w, x))
|/
|/
|/
|/
|/
|/
|/
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
invalid syntax (<string>, line 10)
import numpy as np
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
beta = np.linalg.lstsq(x, y, w)[0]
|/
|/
|/
|/
|/
|/
|/
|/
|/
|/
|/
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
invalid syntax (<string>, line 10)
import numpy as np
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
beta = np.linalg.lstsq(x, y, w)[0]
|/
|/
|/
|/
|/
|/
|/
|/
|/
|/
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
invalid syntax (<string>, line 10)
lipinski_rule_of_five
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
[insert]
return resultimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
name 'result' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
name 'result' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
name 'result' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
name 'result' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol, canonical=True)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol, canonical=True)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol, canonical=True)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol, canonical=True)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol, canonical=True)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
name 'result' is not defined
mape
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
[insert]
return eimport math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = y_hat - y
|/
|/
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
invalid syntax (<string>, line 14)
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = math.fabs(y_hat - y)
|/
|/
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
invalid syntax (<string>, line 14)
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = (y_hat-y)/y_hat
|/
|/
|/
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
invalid syntax (<string>, line 14)
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = y_hat - y
|/
|/
|/
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
invalid syntax (<string>, line 14)
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = y_hat - y
|/
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
invalid syntax (<string>, line 16)
mapping_operator
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
[insert]
return Mimport MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((molecule.n_atoms, molecule.n_atoms))
for i in range(molecule.n_atoms):
for j in range(molecule.n_atoms):
M[i][j] = beads_mappings[i][j]
|/
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
invalid syntax (<string>, line 16)
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((molecule.n_atoms, molecule.n_atoms))
for bead, bead_mapping in beads_mappings.items():
atom_selection = bead_mapping['atom_selection']
atom_selection_atoms = bead_mapping['atom_selection_atoms']
atom_selection_masses = bead_mapping['atom_selection_masses']
atom_selection_masses = atom_selection_masses[atom_selection]
atom_selection_masses = atom_selection_masses[atom_selection_atoms]
atom_selection_masses = atom_selection_masses / np.sum(atom_selection_masses)
atom_selection_masses = atom_selection_masses * bead_mapping['atom_selection_weight']
atom_selection_masses = atom_selection_masses.sum(axis=0)
atom_selection_masses = atom_selection_masses / np.sum(atom_selection_masses)
atom_selection_masses = atom_selection_masses.reshape((molecule.n_atoms, molecule.n_atoms))
M[atom_selection, atom_selection] = atom_selection_masses
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
'list' object has no attribute 'items'
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((len(beads_mappings), len(beads_mappings)))
for i in range(len(beads_mappings)):
for j in range(len(beads_mappings)):
M[i][j] = molecule.GetAtomWithIdx(beads_mappings[i]).GetAtomWithIdx(beads_mappings[j]).GetDegree()
|/
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
invalid syntax (<string>, line 16)
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((len(beads_mappings), len(beads_mappings)))
for i in range(len(beads_mappings)):
for j in range(len(beads_mappings)):
M[i][j] = molecule.GetAtomWithIdx(beads_mappings[i][j]).GetAtomWithIdx(beads_mappings[j][i]).GetDegree()
|/
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
invalid syntax (<string>, line 16)
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((len(molecule), len(molecule)))
for i in range(len(molecule)):
for j in range(len(molecule)):
if beads_mappings[i][j] == 1:
M[i][j] = 1.0
else:
M[i][j] = 0.0
|/
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
invalid syntax (<string>, line 19)
matpow
import numpy as np
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
[insert]
return rimport numpy as np
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.power(x,n)
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.zeros_like(x)
r[:,0] = x[:,0]**n
r[:,1] = x[:,1]**n
r[:,2] = x[:,2]**n
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
index 2 is out of bounds for axis 1 with size 2
import numpy as np
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.zeros_like(x)
r[:,0] = x[:,0]**n
r[:,1] = x[:,1]**n
r[:,2] = x[:,2]**n
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
index 2 is out of bounds for axis 1 with size 2
import numpy as np
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.power(x,n)
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.power(x,n)
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
matrix_factorial
import numpy as np
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
[insert]
return fimport numpy as np
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
if n == 0:
return 1
else:
return n * matrix_factorial(n - 1)
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
f = np.empty([n,n])
for i in range(n):
for j in range(n):
f[i,j] = i**j
|/
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
invalid syntax (<string>, line 14)
import numpy as np
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
f = np.zeros((n, n))
for i in range(n):
for j in range(n):
f[i, j] = f[i, j] * i
f[j, i] = f[i, j]
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
only integer scalar arrays can be converted to a scalar index
import numpy as np
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
f = np.matrix(np.zeros((n,n)))
for i in range(n):
for j in range(n):
f[i,j] = f[j,i]*i
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
only integer scalar arrays can be converted to a scalar index
import numpy as np
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
if n == 1:
return 1
else:
return n * matrix_factorial(n - 1)
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
max-boltz
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
[insert]
return simport math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
s = math.sqrt(T/M)
|/
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 15)
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
s = math.sqrt(T/M)
|/
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 15)
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
s = math.sqrt(M*T/1000)
|/
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 15)
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
s = math.sqrt(T*M/1000)
|/
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 15)
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
s = math.sqrt(M*T/1000)
|/s
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 15)
michaelis
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
[insert]
return v
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax
for t in range(S-1):
v = v * math.exp(-t/Km)
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax * math.exp(-S/Km)
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax/S
v:
v = Km
else:
v = Km
return v
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
unindent does not match any outer indentation level (<string>, line 10)
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax * S * math.exp(-Km * S)
if v 0.1:
v = 0.1
return v
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 10)
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax * S * Km
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
mol_charge
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
[insert]
return chargeimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = Chem.GetFormalCharge(mol)
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = Chem.GetFormalCharge(mol)
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = Chem.GetFormalCharge(mol)
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = Chem.GetFormalCharge(mol)
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = Chem.GetFormalCharge(mol)
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
net_charge
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
[insert]
return chargeimport math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for c in sequence:
charge += math.log10(abs(ord(c) - 65))
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
math domain error
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for c in sequence:
charge += math.log10(c.count('N'))
|/
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
invalid syntax (<string>, line 18)
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for c in sequence:
charge += c
return charge
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
unsupported operand type(s) for +=: 'int' and 'str'
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for c in sequence:
charge += math.log10(c.count('N'))
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
math domain error
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for c in sequence:
charge += math.log10(abs(ord(c) - 97))
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
Success
solve_ode
import numpy as np
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
[insert]
return solimport numpy as np
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
sol = []
for t in t:
sol.append(fn(t,y0))
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
can't multiply sequence by non-int of type 'float'
import numpy as np
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
sol = []
for t in t:
sol.append(fn(t,y0))
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
can't multiply sequence by non-int of type 'float'
import numpy as np
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
sol = []
for t in t:
sol.append(fn(t,y0))
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
can't multiply sequence by non-int of type 'float'
import numpy as np
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
sol = []
for t in t:
sol.append(fn(t,y0))
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
can't multiply sequence by non-int of type 'float'
import numpy as np
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
sol = np.zeros(len(t))
sol[0] = y0
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
setting an array element with a sequence.
ohe
import numpy as np
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
[insert]
return vimport numpy as np
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros(len(a), dtype=np.int32)
|/
|/v
|/
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
invalid syntax (<string>, line 14)
import numpy as np
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros(len(a), dtype=np.int32)
|/ file dstars=0
|/
|/
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
invalid syntax (<string>, line 12)
import numpy as np
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros(len(a), dtype=np.int32)
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
operands could not be broadcast together with shapes (10,) (10,5)
import numpy as np
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros(len(a), dtype=np.int32)
|/ file dstars=0
|/
|/
|/
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
invalid syntax (<string>, line 12)
import numpy as np
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros(len(a), dtype=np.int32)
v[a] = 1
|/ file dstars=0
|/
|/
|/
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
invalid syntax (<string>, line 13)
osmotic_pressure
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
[insert]
return pimport math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = 0.025 # atm /mol
rho = 1.225 # atm /mol
rho_l = 1.225 # atm /mol
rho_h = 1.225 # atm /mol
rho_l = rho_l*math.pow(T,2)
rho_h = rho_h*math.pow(T,2)
rho_l = rho_l*math.pow(T,3)
rho_h = rho_h*math.pow(T,3)
rho_l = rho_l*math.pow(T,4)
rho_h = rho_h*math.pow(T,4)
rho_l = rho_l*math.pow(T,5)
rho_h = rho_h*math.pow(T,5)
rho_l = rho_l*math.pow(T,6)
rho_h = rho_h*math.pow(T,6)
rho_l = rho_l*math.pow(T,7)
rho_h = rho_h*math.pow(T,7)
rho_l = rho_l*math.pow(T,8)
rho_h = rho_h*math.pow(T,8)
rho_l = rho_l*math.pow(T,9)
rho_h = rho_h*math.pow(T,9)
rho_l = rho_l*math.pow(T,10)
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
Success
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = R * math.pow(T,3.0/4.0)
p = p * math.pow(Pi,3.0/4.0)
|/
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
invalid syntax (<string>, line 18)
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = R * math.pow(T,3.0/3.0)
p = p * math.pow(Pi,3.0/3.0)
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
Success
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = R*math.pow(T,3.0/4.0)
|/
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
invalid syntax (<string>, line 17)
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = R*math.pow(T,3.0/4.0)
p = p/math.pi
|/
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
invalid syntax (<string>, line 18)
pair_wise
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
[insert]
return distancesimport mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
pdb = md.load(str(pdb_file))
alpha_carbons = pdb.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.unique()
alpha_carbons_length = len(alpha_carbons)
distances = np.zeros((alpha_carbons_length, alpha_carbons_length))
for i in range(alpha_carbons_length):
for j in range(alpha_carbons_length):
distances[i][j] = pdb.distances[i][j]
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
pdb = md.load(str(pdb_file))
alpha_carbons = pdb.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.unique()
alpha_carbons = list(alpha_carbons)
alpha_carbons.sort()
distances = np.zeros((len(alpha_carbons), len(alpha_carbons)))
for i in range(len(alpha_carbons)):
for j in range(i+1, len(alpha_carbons)):
distances[i][j] = np.linalg.norm(pdb.select('name *[name!= "Carbon"]')[alpha_carbons[i]:alpha_carbons[j]])
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
pdb = md.load(str(pdb_file))
alpha_carbons = pdb.select('name CA')
alpha_carbons = alpha_carbons.sort('CA')
alpha_carbons = alpha_carbons.unique()
alpha_carbons = list(alpha_carbons)
alpha_carbons.sort()
distances = np.zeros((len(alpha_carbons), len(alpha_carbons)))
for i in range(len(alpha_carbons)):
for j in range(len(alpha_carbons)):
if i == j:
continue
distances[i][j] = alpha_carbons[i].distance(alpha_carbons[j])
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
pdb = mdtraj.load(pdb_file)
alpha_carbons = pdb.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
pdb = md.load(pdb_file)
alpha_carbons = pdb.select('name *[name ~ "*"]')
alpha_carbons = alpha_carbons.unique()
alpha_carbons_length = len(alpha_carbons)
distances = np.zeros(alpha_carbons_length)
for i in range(alpha_carbons_length):
alpha_carbon = alpha_carbons[i]
alpha_carbon = alpha_carbon.split()
alpha_carbon = alpha_carbon[0]
alpha_carbon = alpha_carbon[1:]
alpha_carbon = alpha_carbon.split()
alpha_carbon = alpha_carbon[0]
alpha_carbon = alpha_carbon[1:]
alpha_carbon = alpha_carbon.split()
alpha_carbon = alpha_carbon[0]
alpha_carbon = alpha_carbon[1:]
alpha_carbon = alpha_carbon.split()
alpha_carbon = alpha_carbon[0]
alpha_carbon = alpha_carbon[1:]
alpha_carbon = alpha_carbon.split()
alpha_carbon = alpha_carbon[0]
alpha_carbon = alpha_carbon[1:]
alpha_carbon = alpha_carbon.split()
alpha_carbon = alpha_carbon[0]
alpha_carbon = alpha_carbon[1:]
alpha_carbon = alpha_carbon.split()
alpha_carbon = alpha_carbon[0]
alpha_carbon = alpha_carbon[1:]
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
pi
import numpy as np
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
[insert]
return pi_estimport numpy as np
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
pi_est = 1.
for i in range(nsamples):
pi_est *= (2.*np.pi)
pi_est *= np.random.uniform()
return pi_est
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
import numpy as np
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
pi_est = np.pi
for i in range(nsamples):
pi_est = pi_est * 2
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
import numpy as np
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
pi_est = np.pi
pi_est *= nsamples
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
import numpy as np
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
pi_est = np.pi
pi_est *= nsamples
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
import numpy as np
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
pi_est = np.pi
for i in range(nsamples):
pi_est *= 2
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
pib_1d
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
[insert]
return eimport math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e=n*(m*L**2-L**2+hbar*hbar)
|/
|/
|/
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 14)
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e=n-m
for i in range(n+1):
e=e*math.exp(-0.5*hbar*L*i)
|/ file dstars=0
|/
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 14)
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e=math.exp(-0.5*(n*m)/L)*hbar
|/
|/
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 14)
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e=n*(L**2-m*hbar)
|/
|/
|/
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 14)
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e=n-m
if eL: return 0
L: return -hbar
if e==L: return hbar
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 11)
pred_interval
import numpy as np
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
[insert]
return nimport numpy as np
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = len(p)
for i in range(n):
if p[i] pred_level:
return i
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
invalid syntax (<string>, line 10)
import numpy as np
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = int(np.ceil(np.log(p)/np.log(pred_level)))
|/
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
invalid syntax (<string>, line 11)
import numpy as np
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = len(p)
if n == 0:
return 0
if n == 1:
return 1
if n == 2:
return 2
if n == 3:
return 3
if n == 4:
return 4
if n == 5:
return 5
if n == 6:
return 6
if n == 7:
return 7
if n == 8:
return 8
if n == 9:
return 9
if n == 10:
return 10
|/
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
invalid syntax (<string>, line 33)
import numpy as np
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = int(np.floor(np.log(p)/np.log(pred_level)))
|/
|/ file dstars=0
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
invalid syntax (<string>, line 11)
import numpy as np
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = len(p)
for i in range(n):
= pred_level:
return i
|/
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
expected an indented block (<string>, line 10)
pubchem
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
[insert]
return molsimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = 'http://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/similarity?query={}&format=smiles'.format(smiles)
response = requests.get(url)
smiles = response.text
mols = Chem.MolFromSmiles(smiles)
mols = Chem.AddHs(mols)
mols = Chem.MolToSmiles(mols, canonical=True)
mols = Chem.MolFromSmarts(mols)
mols = Chem.RemoveHs(mols)
mols = Chem.RemoveAtoms(mols, rdMolHash.HashesToAtomMap)
mols = Chem.RemoveAtoms(mols, Chem.AtomWithIdx(0))
mols = Chem.RemoveAtoms(mols, Chem.AtomWithIdx(3))
mols = Chem.RemoveAtoms(mols, Chem.AtomWithIdx(6))
mols = Chem.RemoveAtoms(mols, Chem.AtomWithIdx(7))
mols = Chem.RemoveAtoms(mols, Chem.AtomWithIdx(8))
mols = Chem.RemoveAtoms(mols, Chem.AtomWithIdx(9))
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
Python argument types in
rdkit.Chem.rdmolops.AddHs(NoneType)
did not match C++ signature:
AddHs(RDKit::ROMol mol, bool explicitOnly=False, bool addCoords=False, boost::python::api::object onlyOnAtoms=None, bool addResidueInfo=False)
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/search?query={}&format=smiles'.format(smiles)
response = requests.get(url)
mol = Chem.MolFromSmiles(response.text)
mols = [Chem.MolFromSmiles(smiles) for smiles in response.text]
mols = [mol for mol in mols if mol is not None]
mols = [Chem.MolFromSmiles(smiles) for smiles in response.text]
mols = [mol for mol in mols if mol is not None]
mols = [Chem.MolFromSmiles(smiles) for smiles in response.text]
mols = [mol for mol in mols if mol is not None]
mols = [Chem.MolFromSmiles(smiles) for smiles in response.text]
mols = [mol for mol in mols if mol is not None]
mols = [Chem.MolFromSmiles(smiles) for smiles in response.text]
mols = [mol for mol in mols if mol is not None]
mols = [Chem.MolFromSmiles(smiles) for smiles in response.text]
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
mols = Chem.MolFromSmiles(smiles)
mols = [Chem.MolToSmiles(mol) for mol in mols]
mols = Chem.MolStandardize(mols)
mols = [Chem.MolFromSmiles(smiles) for smiles in mols]
mols = Chem.MolStandardize(mols)
mols = [Chem.MolFromSmiles(smiles) for smiles in mols]
mols = Chem.MolStandardize(mols)
mols = [Chem.MolFromSmiles(smiles) for smiles in mols]
mols = Chem.MolStandardize(mols)
mols = [Chem.MolFromSmiles(smiles) for smiles in mols]
mols = Chem.MolStandardize(mols)
mols = [Chem.MolFromSmiles(smiles) for smiles in mols]
mols = Chem.MolStandardize(mols)
mols = [Chem.MolFromSmiles(smiles) for smiles in mols]
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
'Mol' object is not iterable
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/search?query={}&format=sdf'.format(smiles)
response = requests.get(url)
data = response.json()
mols = []
for item in data['results']:
mols.append(Chem.MolFromSmiles(item['smiles'])) # Convert SMILES to Mol
mols = rdMolDescriptors.MolDescriptors.GetMorganFingerprintAsBitVect(mols, 2)
mols = Scaffolds.MolWt(mols)
mols = Scaffolds.MolWt(mols)
mols = Scaffolds.MolWt(mols)
mols = Scaffolds.MolWt(mols)
mols = Scaffolds.MolWt(mols)
mols = Scaffolds.MolWt(mols)
mols = Scaffolds.MolWt(mols)
mols = Scaffolds.MolWt(mols)
mols = Scaffolds.MolWt(mols)
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
Expecting value: line 1 column 1 (char 0)
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = 'http://rest.pubchem.net/api/similarity?smiles=' + smiles
response = requests.get(url)
data = response.json()
mols = data['results']
mols = [Chem.MolFromSmiles(smi) for smi in mols]
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
HTTPConnectionPool(host='rest.pubchem.net', port=80): Max retries exceeded with url: /api/similarity?smiles=CC=C=C(C(=O)N) (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f76f3958400>: Failed to establish a new connection: [Errno -2] Name or service not known'))
pyscf_energy
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
[insert]
return ground_energyimport pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom,basis=basis)
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [['H', (0., 0. , 0.)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
invalid syntax (<string>, line 29)
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom,basis=basis)
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [atom.split()]
mol.basis = basis
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [atom.split()]
mol.basis = basis
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [atom.split()]
mol.basis = basis
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [atom.split()]
mol.basis = basis
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [atom.split()]
mol.basis = basis
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [atom.split()]
mol.basis = basis
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [atom.split()]
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom,basis=basis)
mol.verbose = 0
mol.output = None
mol.atom = [['H', (0., 0. , 0.)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
invalid syntax (<string>, line 28)
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom,basis=basis)
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [atom.name, atom.x, atom.y, atom.z]
mol.basis = basis
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [atom.name, atom.x, atom.y, atom.z]
mol.basis = basis
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [atom.name, atom.x, atom.y, atom.z]
mol.basis = basis
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [atom.name, atom.x, atom.y, atom.z]
mol.basis = basis
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [atom.name, atom.x, atom.y, atom.z]
mol.basis = basis
mol.build()
mol.verbose = 0
mol.output = None
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom,basis=basis)
mol.build()
mol.kernel()
ground_energy = mol.energy_nuc()
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
qed
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
[insert]
return resultimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
name 'result' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
name 'result' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
name 'result' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
name 'result' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
name 'result' is not defined
quantile
import numpy as np
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
[insert]
return resultimport numpy as np
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
result = np.zeros_like(a)
q] = np.nan
|/|/
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
unindent does not match any outer indentation level (<string>, line 9)
import numpy as np
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
result = np.percentile(a, q)
|/|/|/
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
invalid syntax (<string>, line 13)
import numpy as np
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
result = np.zeros_like(a)
q))]
|/|/
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
unmatched ')' (<string>, line 9)
import numpy as np
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
result = np.zeros_like(a)
result[np.where(a=q)] = a[np.where(a=q)]
q)]
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
unmatched ')' (<string>, line 10)
import numpy as np
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
result = np.zeros_like(a)
result[np.where(a=q)] = a[np.where(a=q)]
q)]
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
unmatched ')' (<string>, line 10)
random_walk
import numpy as np
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
[insert]
return trajimport numpy as np
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = []
for i in range(N):
x1 = x0 + a * np.random.randn()
traj.append([x0, x1])
x0 = x1
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = []
for i in range(N):
x1 = x0 + a * np.random.random()
traj.append([x0, x1])
x0 = x1
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = []
for i in range(N):
traj.append(x0)
x0 = x0 + a
|/ file dstars=1
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
invalid syntax (<string>, line 16)
import numpy as np
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = []
for i in range(N):
traj.append([x0])
x0 += a
|/
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
invalid syntax (<string>, line 18)
import numpy as np
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = []
for i in range(N):
x1 = x0 + a * np.random.randn(1)
traj.append([x0, x1])
x0 = x1
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
loop of ufunc does not support argument 0 of type numpy.ndarray which has no callable log method
rank
import numpy as np
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
[insert]
return rimport numpy as np
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U,S,V = np.linalg.svd(M)
r = np.sum(np.diag(S))
|/
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
invalid syntax (<string>, line 14)
import numpy as np
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M)
r = np.argsort(s)
|/
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
invalid syntax (<string>, line 14)
import numpy as np
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M)
0)[0]
|/
|/
|/
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
unindent does not match any outer indentation level (<string>, line 9)
import numpy as np
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M)
rank = s.argmax()
|/
|/
|/
|/
|/
|/
|/
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
invalid syntax (<string>, line 14)
import numpy as np
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U,S,V = np.linalg.svd(M)
r = np.argsort(np.abs(S))
|/
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
invalid syntax (<string>, line 14)
remove-water
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
[insert]
return new_trajimport mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file)
traj.top = traj.top.remove_solvent_from_topology(top_file)
new_traj = md.load(traj)
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
"top" argument is required for load_trr
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file)
top = md.load(top_file)
new_traj = traj.remove_solvent_from_topology(top)
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
"top" argument is required for load_trr
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file)
top = md.load(top_file)
new_traj = traj.remove_solvent_from_topology(top)
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
"top" argument is required for load_trr
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
new_traj = md.load(traj_file)
new_traj.top = md.load(top_file)
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
"top" argument is required for load_trr
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
new_traj = md.load(traj_file)
new_traj.top = md.load(top_file)
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
"top" argument is required for load_trr
rms_velocity
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
[insert]
return v_rms
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
v_rms = math.sqrt(T*m*m/3.0)
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
v_rms = math.sqrt(T*m*m/3.0)
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
v_rms = math.sqrt(T*m*m/T)
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
v_rms = math.sqrt(T*m*m/(T*T))
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
v_rms = math.sqrt(T*m*m/T)
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
rmse
import numpy as np
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
[insert]
return eimport numpy as np
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.power(a-b,2)
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt((a-b)**2).mean()
|/
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
invalid syntax (<string>, line 11)
import numpy as np
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt((a-b)**2).mean()
|/
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
invalid syntax (<string>, line 11)
import numpy as np
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt((a-b)**2).mean()
|/
|/
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
invalid syntax (<string>, line 11)
import numpy as np
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt((a-b)**2)
|/
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
invalid syntax (<string>, line 11)
rog
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
[insert]
return rgimport mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
pdb = md.load(pdb_file)
rg = md.compute_radius_of_gyration(pdb)
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
module 'mdtraj' has no attribute 'compute_radius_of_gyration'
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
pdb = md.load(pdb_file)
rg = protein_radius(pdb)
return rg
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
name 'protein_radius' is not defined
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
pdb = md.load(pdb_file)
rg = mdtraj.distances.compute_radius_of_gyration(pdb)
|/
|/
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
invalid syntax (<string>, line 17)
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
pdb = md.load(pdb_file)
rg = protein_radius(pdb)
return rg
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
name 'protein_radius' is not defined
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
pdb = md.load(pdb_file)
rg = protein_radius_of_gyration_from_pdb(pdb)
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
name 'protein_radius_of_gyration_from_pdb' is not defined
sasa
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
[insert]
return sasaimport mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
pdb = md.load(pdb_file)
sasa = pdb.select('CA')
sasa = sasa.sum(axis=1).reshape(pdb.n_atoms, 1)
|/
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
invalid syntax (<string>, line 16)
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
pdb = md.load(pdb_file)
sasa = pdb.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
'Trajectory' object has no attribute 'select'
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
pdb = md.load(pdb_file)
sasa = pdb.select('resname CA')
sasa.rename("CA")
|/
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
invalid syntax (<string>, line 16)
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
pdb = mdtraj.load(pdb_file)
sasa = pdb.select("resname like 'SASA%'")
sasa.compute_volume()
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
name 'mdtraj' is not defined
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
pdb = md.load(pdb_file)
sasa = pdb.select('CA')
sasa = sasa.sum(axis=1).reshape(pdb.n_atoms, 1)
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
'Trajectory' object has no attribute 'select'
scaffold
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
[insert]
return scaffold_smilesimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
scaffold_smiles = Chem.MolToSmiles(Chem.MolFromSmiles(smiles))
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
scaffold_smiles = Chem.MolToSmiles(Chem.MolFromSmiles(smiles))
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
scaffold_smiles = Chem.MolToSmiles(mol)
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
scaffold_smiles = Chem.MolToSmiles(Chem.MolFromSmiles(smiles))
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
scaffold_smiles = Chem.MolToSmiles(Chem.MolFromSmiles(smiles))
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
Success
seq-align
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
[insert]
return alignedfrom Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
aln = Align.MultipleSeqAlignment([seq1, seq2], gap_char="-")
aln.set_flags(aln.get_flags() | Align.DONT_OVERLAP)
aln.set_score_mode(Align.SCORE_ABSOLUTE)
aln.set_evalue(0.0)
aln.set_evalue_threshold(0.0)
aln.set_score_file("blast.out")
aln.set_evalue_cutoff(0.05)
aln.set_evalue_cutoff_threshold(0.05)
aln.set_evalue_cutoff_threshold(0.05)
aln.set_evalue_cutoff_threshold(0.05)
aln.set_evalue_cutoff_threshold(0.05)
aln.set_evalue_cutoff_threshold(0.05)
aln.set_evalue_cutoff_threshold(0.05)
aln.set_evalue_cutoff_threshold(0.05)
aln.set_evalue_cutoff_threshold(0.05)
aln.set_evalue_cutoff_threshold(0.05)
aln.set_evalue_cutoff_threshold(0.05)
aln.set_evalue_cutoff_threshold(0.05)
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
__init__() got an unexpected keyword argument 'gap_char'
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
aln = Align.MultipleSeqAlignment([seq1, seq2], gap_open='-', gap_extend='-')
return aln.get_alignment_string()
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
__init__() got an unexpected keyword argument 'gap_open'
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
aln = Align.MultipleSeqAlignment([SeqIO.to_dict(SeqRecord(Seq(seq1), "fasta")), SeqIO.to_dict(SeqRecord(Seq(seq2), "fasta"))])
aln.set_flags(AlignInfo.SMART_AA_NAMES)
aln.set_flags(AlignInfo.SMART_aa)
aln.set_flags(AlignInfo.INTRON)
aln.set_flags(AlignInfo.INTRON)
aln.set_flags(AlignInfo.INTRON)
aln.set_flags(AlignInfo.INTRON)
aln.set_flags(AlignInfo.INTRON)
aln.set_flags(AlignInfo.INTRON)
aln.set_flags(AlignInfo.INTRON)
aln.set_flags(AlignInfo.INTRON)
aln.set_flags(AlignInfo.INTRON)
aln.set_flags(AlignInfo.INTRON)
aln.set_flags(AlignInfo.INTRON)
aln.set_flags(AlignInfo.INTRON)
aln.set_flags(AlignInfo.INTRON)
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
name 'SeqRecord' is not defined
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
aln = AlignIO.read(seq1, 'fasta')
aln = AlignIO.read(seq2, 'fasta')
aln = AlignIO.read(aln, 'blast')
aln = AlignIO.read(aln, 'blastp')
aln = AlignIO.read(aln, 'blastx')
aln = AlignIO.read(aln, 'blastn')
aln = AlignIO.read(aln, 'blastx')
aln = AlignIO.read(aln, 'blastn')
aln = AlignIO.read(aln, 'blastx')
aln = AlignIO.read(aln, 'blastn')
aln = AlignIO.read(aln, 'blastx')
aln = AlignIO.read(aln, 'blastn')
aln = AlignIO.read(aln, 'blastx')
aln = AlignIO.read(aln, 'blastn')
aln = AlignIO.read(aln, 'blastx')
aln = AlignIO.read(aln, 'blastn')
aln = AlignIO.read(aln, 'blastx')
aln = AlignIO.read(aln, 'blastn')
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
name 'AlignIO' is not defined
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
aln = Align.MultipleSeqAlignment([seq1, seq2], gap_char="-")
aln.set_flags(aln.get_flags() | Align.AUTO_SEQUENCE)
aln.set_score_mode(aln.get_score_mode() | Align.SCORE_ALIGNMENT_SCORE)
aln.set_evalue(0)
aln.set_score_func(aln.get_score_func() | Align.SCORE_ALIGNMENT_SCORE)
aln.set_evalue_threshold(0)
aln.set_evalue_cutoff(0)
aln.set_score_cutoff(0)
aln.set_evalue_cutoff(0)
aln.set_score_cutoff(0)
aln.set_evalue_cutoff(0)
aln.set_score_cutoff(0)
aln.set_evalue_cutoff(0)
aln.set_score_cutoff(0)
aln.set_evalue_cutoff(0)
aln.set_score_cutoff(0)
aln.set_evalue_cutoff(0)
aln.set_score_cutoff(0)
aln.set_evalue_cutoff(0)
aln.set_score_cutoff(0)
aln.set_evalue_cutoff(0)
aln.set_score_cutoff(0)
aln.set_evalue_cutoff(0)
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
__init__() got an unexpected keyword argument 'gap_char'
seq-trans
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
[insert]
return prot_seqfrom Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq)
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq)
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq)
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq)
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq)
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
sequence
import numpy as np
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
[insert]
return ximport numpy as np
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
x = np.arange(s,e,l)
|/
|/ file dstars=0
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
invalid syntax (<string>, line 14)
import numpy as np
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
s=np.float(s)
e=np.float(e)
l=np.float(l)
x=np.arange(s,e,l)
|/
|/
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
invalid syntax (<string>, line 18)
import numpy as np
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
name 'x' is not defined
import numpy as np
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
x = np.arange(s,e,l)
|/
|/|/
|/
|/
|/
|/
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
invalid syntax (<string>, line 14)
import numpy as np
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
name 'x' is not defined
sle
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
[insert]
return ximport sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
eqns = sympy.sympify(eqns)
x = sympy.symbols('x')
eqns = eqns.subs([('a_0x_0', 'c0'), ('a_1x_0', 'c1')])
eqns = eqns.subs([('b_0x_1', 'c0'), ('b_1x_1', 'c1')])
eqns = eqns.subs([('x_0', 'c0'), ('x_1', 'c1')])
eqns = eqns.subs([('x_0', 'c0'), ('x_1', 'c1')])
eqns = eqns.subs([('x_0', 'c0'), ('x_1', 'c1')])
eqns = eqns.subs([('x_0', 'c0'), ('x_1', 'c1')])
eqns = eqns.subs([('x_0', 'c0'), ('x_1', 'c1')])
eqns = eqns.subs([('x_0', 'c0'), ('x_1', 'c1')])
eqns = eqns.subs([('x_0', 'c0'), ('x_1', 'c1')])
eqns = eqns.subs([('x_0', 'c0'), ('x_1', 'c1')])
eqns = eqns.subs([('x_0', 'c0'), ('x_1', 'c1')])
eqns = eqns.subs([('x_0', 'c0'), ('x_1', 'c1')])
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
eqns = sympy.sympify(eqns)
x = sympy.symbols('x')
eqns = eqns.subs({x:sympy.symbols('a_0x_0 + b_0x_1 = c0')})
eqns = eqns.subs({x:sympy.symbols('a_1x_0 + b_1x_1 = c1')})
eqns = eqns.subs({x:sympy.symbols('b_0x_0 = c0')})
eqns = eqns.subs({x:sympy.symbols('b_1x_0 = c1')})
eqns = eqns.subs({x:sympy.symbols('a_0x_0 = c0')})
eqns = eqns.subs({x:sympy.symbols('a_1x_0 = c1')})
eqns = eqns.subs({x:sympy.symbols('b_0x_1 = c0')})
eqns = eqns.subs({x:sympy.symbols('b_1x_1 = c1')})
eqns = eqns.subs({x:sympy.symbols('a_0x_1 = c0')})
eqns = eqns.subs({x:sympy.symbols('a_1x_1 = c1')})
eqns = eqns.subs({x:sympy.symbols('b_0x_0 = c0')})
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
eqns = sympy.sympify(eqns)
x = sympy.symbols('x')
eqns = eqns.subs({x:sympy.symbols('a_0x_0 + b_0x_1 = c0')})
eqns = eqns.subs({x:sympy.symbols('a_1x_0 + b_1x_1 = c1')})
eqns = eqns.subs({x:sympy.symbols('b_0x_0 = c0')})
eqns = eqns.subs({x:sympy.symbols('b_1x_0 = c1')})
eqns = eqns.subs({x:sympy.symbols('b_0x_1 = c0')})
eqns = eqns.subs({x:sympy.symbols('b_1x_1 = c1')})
eqns = eqns.subs({x:sympy.symbols('c_0x_0 = c0')})
eqns = eqns.subs({x:sympy.symbols('c_1x_0 = c1')})
eqns = eqns.subs({x:sympy.symbols('c_0x_1 = c0')})
eqns = eqns.subs({x:sympy.symbols('c_1x_1 = c1')})
eqns = eqns.subs({x:sympy.symbols('c_0x_0 = c0')})
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
eqns = sympy.sympify(eqns)
a = eqns[0]
b = eqns[1]
c = eqns[2]
d = eqns[3]
e = eqns[4]
f = eqns[5]
g = eqns[6]
h = eqns[7]
i = eqns[8]
j = eqns[9]
k = eqns[10]
l = eqns[11]
m = eqns[12]
n = eqns[13]
o = eqns[14]
p = eqns[15]
q = eqns[16]
r = eqns[17]
s = eqns[18]
t = eqns[19]
u = eqns[20]
v = eqns[21]
w = eqns[22]
x = sympy.Matrix([[a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p],[q,r,s,t,u,v,w,x,y,z,w]])
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
eqns = sympy.sympify(eqns)
x = sympy.symbols('x')
eqns = eqns.subs({x:sympy.symbols('a_0x_0 + b_0x_1 = c0')})
eqns = eqns.subs({x:sympy.symbols('a_1x_0 + b_1x_1 = c1')})
eqns = eqns.subs({x:sympy.symbols('b_0x_0 = c0')})
eqns = eqns.subs({x:sympy.symbols('b_1x_0 = c1')})
eqns = eqns.subs({x:sympy.symbols('a_0x_0 = c0')})
eqns = eqns.subs({x:sympy.symbols('a_1x_0 = c1')})
eqns = eqns.subs({x:sympy.symbols('b_0x_1 = c0')})
eqns = eqns.subs({x:sympy.symbols('b_1x_1 = c1')})
eqns = eqns.subs({x:sympy.symbols('a_0x_1 = c0')})
eqns = eqns.subs({x:sympy.symbols('a_1x_1 = c1')})
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
spectral_r
import numpy as np
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
[insert]
return sradiusimport numpy as np
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
sradius = np.sum(a**2,axis=1)
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
sradius = np.sum(a**2, axis=1)
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
sradius = np.sum(a**2, axis=1)
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
sradius = np.sum(a**2)
|/
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
invalid syntax (<string>, line 11)
import numpy as np
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
sradius = np.sum(a**2)
|/
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
invalid syntax (<string>, line 11)
find_peaks
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
[insert]
return wavenumbersimport numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
peaks, _ = scipy.signal.find_peaks(abs_spectrum, height=npeaks)
wavenumbers = []
for peak in peaks:
wavenumbers.append(peak[0])
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
`x` must be a 1-D array
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
peak_positions, _ = scipy.signal.find_peaks(abs_spectrum, height=npeaks)
peak_positions = np.asarray(peak_positions)
peak_positions.sort()
peak_positions = peak_positions[::-1]
peak_positions = peak_positions[:npeaks]
return peak_positions
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
`x` must be a 1-D array
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
peaks, _ = scipy.signal.find_peaks(abs_spectrum, height=npeaks)
peaks = np.asarray(peaks)
peaks.sort()
peaks = peaks[:npeaks]
return peaks
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
`x` must be a 1-D array
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
peaks, _ = scipy.signal.find_peaks(abs_spectrum, height=npeaks)
peaks = peaks[::-1]
peaks = [peaks[i] for i in xrange(len(peaks))]
return peaks
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
`x` must be a 1-D array
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
peaks, _ = scipy.signal.find_peaks(abs_spectrum, height=npeaks)
wavenumbers = []
for p in peaks:
wavenumbers.append(p[0])
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
`x` must be a 1-D array
speed_of_sound
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
[insert]
return s
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
s = m * gamma * T
if __name__ == "__main__":
T = int(sys.argv[1])
m = float(sys.argv[2])
gamma = float(sys.argv[3])
print speed_of_sound(T,m,gamma)
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 16)
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
s = m*T*math.exp(-gamma*T)
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
s = T*m*math.exp(-gamma*T)
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
s = T*m*gamma
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
s = T*m*gamma
s = math.floor(s)
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
substructure
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
[insert]
return idximport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
mol_list = Chem.MolFromSmiles(smiles)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.RemoveHs(mol_list)
mol_list = Chem.RemoveAtoms(mol_list, 1)
mol_list = Chem.RemoveAtoms(mol_list, 2)
mol_list = Chem.RemoveAtoms(mol_list, 3)
mol_list = Chem.RemoveAtoms(mol_list, 4)
mol_list = Chem.RemoveAtoms(mol_list, 5)
mol_list = Chem.RemoveAtoms(mol_list, 6)
mol_list = Chem.RemoveAtoms(mol_list, 7)
mol_list = Chem.RemoveAtoms(mol_list, 8)
mol_list = Chem.RemoveAtoms(mol_list, 9)
mol_list = Chem.RemoveAtoms(mol_list, 10)
mol_list = Chem.RemoveAtoms(mol_list, 11)
mol_list = Chem.RemoveAtoms(mol_list, 12)
mol_list = Chem.RemoveAtoms(mol_list, 13)
mol_list = Chem.RemoveAtoms(mol_list, 14)
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
mol_list = Chem.MolFromSmiles(smiles)
mol_list = [Chem.MolFromSmiles(smiles) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
mol_list = Chem.MolFromSmiles(smiles)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
mol_list = Chem.MolFromSmiles(smiles)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.RemoveHs(mol_list)
mol_list = Chem.RemoveAtoms(mol_list, 1)
mol_list = Chem.RemoveAtoms(mol_list, 2)
mol_list = Chem.RemoveAtoms(mol_list, 3)
mol_list = Chem.RemoveAtoms(mol_list, 4)
mol_list = Chem.RemoveAtoms(mol_list, 5)
mol_list = Chem.RemoveAtoms(mol_list, 6)
mol_list = Chem.RemoveAtoms(mol_list, 7)
mol_list = Chem.RemoveAtoms(mol_list, 8)
mol_list = Chem.RemoveAtoms(mol_list, 9)
mol_list = Chem.RemoveAtoms(mol_list, 10)
mol_list = Chem.RemoveAtoms(mol_list, 11)
mol_list = Chem.RemoveAtoms(mol_list, 12)
mol_list = Chem.RemoveAtoms(mol_list, 13)
mol_list = Chem.RemoveAtoms(mol_list, 14)
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
mol_list = Chem.MolFromSmiles(smiles)
mol_list = [Chem.MolFromSmiles(smiles) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
tanimoto
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
[insert]
return simport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
scaffold = Scaffolds.MurckoScaffold()
scaffold.Compute2DCoords()
scaffold.SetProp("Compute2DCoords", True)
scaffold.SetProp("NumBits", bits)
scaffold.SetProp("NumAtomPairs", len(smiles_list))
scaffold.SetProp("NumExplicitHs", 0)
scaffold.SetProp("NumImplicitHs", 0)
scaffold.SetProp("NumRotatableBonds", 0)
scaffold.SetProp("NumPeriodicBonds", 0)
scaffold.SetProp("NumBonds", 0)
scaffold.SetProp("NumBondBonds", 0)
scaffold.SetProp("NumHs", 0)
scaffold.SetProp("NumHsAtomPairs", 0)
scaffold.SetProp("NumHsBonds", 0)
scaffold.SetProp("NumHsBondBonds", 0)
scaffold.SetProp("NumHsBondBondBonds", 0)
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffold'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
scaffold = Scaffolds.MurckoScaffold()
scaffold.Compute2DCoords()
scaffold.SetProp("Compute2DCoords", True)
scaffold.SetProp("NumBits", bits)
scaffold.SetProp("MurckoPhi", True)
scaffold.SetProp("MurckoPhiBits", bits)
scaffold.SetProp("MurckoPhiPrecision", bits)
scaffold.SetProp("MurckoPhiMinBits", bits)
scaffold.SetProp("MurckoPhiMaxBits", bits)
scaffold.SetProp("MurckoPhiSeed", 0)
scaffold.SetProp("MurckoPhiSeedBits", bits)
scaffold.SetProp("MurckoPhiSeedPrecision", bits)
scaffold.SetProp("MurckoPhiSeedMinBits", bits)
scaffold.SetProp("MurckoPhiSeedMaxBits", bits)
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffold'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
scaffold = Scaffolds.MurckoScaffold()
scaffold.SetProp("GenerateMurckoFlag", 0)
scaffold.SetProp("MurckoBits", bits)
scaffold.SetProp("MurckoPhi", 3)
scaffold.SetProp("MurckoMinVal", 0)
scaffold.SetProp("MurckoSeed", 0)
scaffold.SetProp("MurckoSeed2", 0)
scaffold.SetProp("MurckoSeed3", 0)
scaffold.SetProp("MurckoSeed4", 0)
scaffold.SetProp("MurckoSeed5", 0)
scaffold.SetProp("MurckoSeed6", 0)
scaffold.SetProp("MurckoSeed7", 0)
scaffold.SetProp("MurckoSeed8", 0)
scaffold.SetProp("MurckoSeed9", 0)
scaffold.SetProp("MurckoSeed10", 0)
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffold'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
scaffold = Scaffolds.MurckoScaffold()
scaffold.Compute2DCoords()
scaffold.SetProp("Compute2DCoords", True)
scaffold.SetProp("MurckoScaffoldParams.NumBits", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsError", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsWarning", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsAccuracy", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsAccuracyError", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsAccuracyWarning", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsAccuracyAccuracy", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsAccuracyAccuracyError", bits)
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffold'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
scaffold = Scaffolds.MurckoScaffold()
scaffold.Compute2DCoords()
scaffold.SetProp("Compute2DCoords", True)
scaffold.SetProp("MurckoScaffoldParams.NumBits", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsFingerprint", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsAtom", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsBond", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsAngle", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsBondAngle", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsHBond", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsHAngle", bits)
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffold'
unbdistance
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
[insert]
return resultimport mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_resid=md.resids[lig_str]
lig_traj = md.load(traj,top=lig_resid).get_frame(0)
lig_traj = lig_traj[lig_traj.select('resname '+lig_str)]
lig_traj = lig_traj[lig_traj.select('name '+lig_str)]
lig_traj = lig_traj[lig_traj.select('chain '+lig_str)]
lig_traj = lig_traj[lig_traj.select('chain '+lig_str)]
lig_traj = lig_traj[lig_traj.select('chain '+lig_str)]
lig_traj = lig_traj[lig_traj.select('chain '+lig_str)]
lig_traj = lig_traj[lig_traj.select('chain '+lig_str)]
lig_traj = lig_traj[lig_traj.select('chain '+lig_str)]
lig_traj = lig_traj[lig_traj.select('chain '+lig_str)]
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_resid=lig_str.split("_")
lig_resid=lig_resid[0]
lig_resid=lig_resid[1:]
lig_resid=lig_resid.split(":")
lig_resid=lig_resid[0]
lig_resid=lig_resid.split("-")
lig_resid=lig_resid[0]
lig_resid=lig_resid.split("(")
lig_resid=lig_resid[0]
lig_resid=lig_resid.split(")")
lig_resid=lig_resid[0]
lig_resid=lig_resid.split("+")
lig_resid=lig_resid[0]
lig_resid=lig_resid.split("-")
lig_resid=lig_resid[0]
lig_resid=lig_resid.split("*")
lig_resid=lig_resid[0]
lig_resid=lig_resid.split("=")
lig_resid=lig_resid[0]
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_atoms = traj.resids[lig_str]
lig_atoms_center = lig_atoms.center()
lig_atoms_center = np.array(lig_atoms_center)
lig_atoms_center = lig_atoms_center.reshape((1,3))
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_str = lig_str.upper()
lig_atoms = md.get_atoms(traj,resname=lig_str)
lig_atoms = lig_atoms.reshape((-1,3))
lig_atoms[:,0] += traj[0].xyz[0]
lig_atoms[:,1] += traj[0].xyz[1]
lig_atoms[:,2] += traj[0].xyz[2]
lig_atoms[:,0] /= len(traj)
lig_atoms[:,1] /= len(traj)
lig_atoms[:,2] /= len(traj)
lig_atoms[:,0] -= traj[0].xyz[0]
lig_atoms[:,1] -= traj[0].xyz[1]
lig_atoms[:,2] -= traj[0].xyz[2]
lig_atoms[:,0] /= len(traj)
lig_atoms[:,1] /= len(traj)
lig_atoms[:,2] /= len(traj)
lig_atoms[:,0] -= traj[0].xyz[0]
lig_atoms[:,1] -= traj[0].xyz[1]
lig_atoms[:,2] -= traj[0].xyz[2]
lig_atoms[:,0] /= len(traj)
lig_atoms[:,1] /= len(traj)
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_traj = md.load(lig_str)
lig_traj.compute_center_of_mass()
lig_traj.save('lig_traj.xyz')
lig_traj = md.load('lig_traj.xyz')
lig_traj.compute_center_of_mass()
lig_traj.save('lig_traj.xyz')
lig_traj = md.load('lig_traj.xyz')
lig_traj.compute_center_of_mass()
lig_traj.save('lig_traj.xyz')
lig_traj = md.load('lig_traj.xyz')
lig_traj.compute_center_of_mass()
lig_traj.save('lig_traj.xyz')
lig_traj = md.load('lig_traj.xyz')
lig_traj.compute_center_of_mass()
lig_traj.save('lig_traj.xyz')
lig_traj = md.load('lig_traj.xyz')
lig_traj.compute_center_of_mass()
lig_traj.save('lig_traj.xyz')
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'